Example #1
0
        /// <summary>
        /// Constructor to create a new MSBuild.BuildItem and add it to the project
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        internal ProjectElement(ProjectNode project, string itemPath, string itemType)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (String.IsNullOrEmpty(itemPath))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "itemPath");
            }

            if (String.IsNullOrEmpty(itemType))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "itemType");
            }

            this.itemProject = project;

            // create and add the item to the project

            this.item = project.BuildProject.AddNewItem(itemType, Microsoft.Build.BuildEngine.Utilities.Escape(itemPath));
            this.itemProject.SetProjectFileDirty(true);
            this.RefreshProperties();
        }
        public void BasicProxying()
        {          
            BuildItemGroup ig = new BuildItemGroup();
            BuildItem i1 = new BuildItem("name1", "value1");
            i1.SetMetadata("myMetaName", "myMetaValue");
            BuildItem i2 = new BuildItem("name2", "value2");
            ig.AddItem(i1);
            ig.AddItem(i2);

            BuildItemGroupProxy proxy = new BuildItemGroupProxy(ig);

            // Gather everything into our own table
            Hashtable list = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach (DictionaryEntry item in proxy)
            {
                list.Add(item.Key, item.Value);
            }

            // Check we got all the items
            Assertion.AssertEquals(2, list.Count);
            Assertion.AssertEquals("value1", ((TaskItem)list["name1"]).ItemSpec);
            Assertion.AssertEquals("value2", ((TaskItem)list["name2"]).ItemSpec);

            // Check they have all their metadata
            int builtInMetadata = FileUtilities.ItemSpecModifiers.All.Length;
            Assertion.AssertEquals(1 + builtInMetadata, ((TaskItem)list["name1"]).MetadataCount);
            Assertion.AssertEquals(0 + builtInMetadata, ((TaskItem)list["name2"]).MetadataCount);
            Assertion.AssertEquals("myMetaValue", ((TaskItem)list["name1"]).GetMetadata("myMetaName"));
        }
        internal BuildItemProxy(object buildItem)
        {
            instance = (Microsoft.Build.BuildEngine.BuildItem)buildItem;

            // I am not sure what's going on here, but sometimes, in particular when the project is initialized
            // the build item is not what we are getting here, but rather the child element
            // 'get_ParentPersistedItem" gives us what we need
            var persisted_instance = (BuildItem)typeof(BuildItem)
                .InvokeMember("get_ParentPersistedItem", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, instance, new object[] { });
            if (persisted_instance != null)
                instance = persisted_instance;

            buildItemGroup = (BuildItemGroup)typeof(BuildItem)
                .InvokeMember("get_ParentPersistedItemGroup", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
                null, instance, new object[] { });

            int i = -1;
            foreach (BuildItem item in buildItemGroup)
            {
                i++;
                if (item == instance)
                {
                    index = i;
                    break;
                }
            }

            Include = instance.Include;
            Type = instance.Name;
        }
        public static bool IsOrphaned(BuildItem buildItem, ProjectBase owner)
        {
            bool considerBuildItem = (buildItem.Name == "Compile" || buildItem.Name == "Content" || buildItem.Name == "None");

            if(!considerBuildItem)
            {
                if (owner is VisualStudioProject)
                {
                    var asVisualStudioProject = owner as VisualStudioProject;

                    if (!considerBuildItem && buildItem.Name == asVisualStudioProject.DefaultContentAction)
                    {
                        considerBuildItem = true;
                    }
                }
            }

            if (considerBuildItem)
            {
                // characters like '%' are encoded, so we have to decode them:
                string relativeName = System.Web.HttpUtility.UrlDecode( buildItem.Include);
                string fullName = owner.MakeAbsolute(relativeName);
                return !FileManager.FileExists(fullName) && buildItem.Name != "ProjectReference";
            }
            return false;
        }
        protected override void ResolveReference()
        {
            if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
            {
                return;
            }

            MSBuild.BuildItemGroup group = this.ProjectMgr.BuildProject.GetEvaluatedItemsByName(ProjectFileConstants.ReferencePath);
            if (group != null)
            {
                IEnumerator enumerator = group.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    MSBuild.BuildItem item = (MSBuild.BuildItem)enumerator.Current;

                    string fullPath = this.GetFullPathFromPath(item.FinalItemSpec);

                    System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(fullPath);

                    // Try with full assembly name and then with weak assembly name.
                    if (String.Compare(name.FullName, this.assemblyName.FullName, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(name.Name, this.assemblyName.Name, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // set the full path now.
                        this.assemblyPath         = fullPath;
                        this.resolvedAssemblyName = name;

                        // No hint path is needed since the assembly path will always be resolved.
                        return;
                    }
                }
            }
        }
Example #6
0
        public void Initialize()
        {
            // Create some items and place them in a dictionary
            // Add some include information so that when we check the final 
            // item spec we can verify that the item was recreated properly
            BuildItem[] buildItems = new BuildItem[1];
            buildItems[0] = new BuildItem("BuildItem1", "Item1");
            Dictionary<object, object> dictionary1 = new Dictionary<object, object>();
            dictionary1.Add("Target1", buildItems);
            Hashtable resultsByTarget1 = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultsByTarget1.Add("Target1", Target.BuildState.CompletedSuccessfully);

            Dictionary<object, object> dictionary2 = new Dictionary<object, object>();
            dictionary2.Add("Target2", buildItems);
            dictionary2.Add("Target3", null);
            Hashtable resultsByTarget2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultsByTarget2.Add("Target2", Target.BuildState.CompletedSuccessfully);
            resultsByTarget2.Add("Target3", Target.BuildState.CompletedSuccessfully);

            Dictionary<object, object> dictionary3 = new Dictionary<object, object>();
            dictionary3.Add("Target4", buildItems);
            Hashtable resultsByTarget3 = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultsByTarget3.Add("Target4", Target.BuildState.Skipped);

            resultWith0Outputs = new BuildResult(new Hashtable(), new Hashtable(StringComparer.OrdinalIgnoreCase), true, 1, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
            resultWith1Outputs = new BuildResult(dictionary1, resultsByTarget1, true, 1, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
            resultWith2Outputs = new BuildResult(dictionary2, resultsByTarget2, true, 1, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
            uncacheableResult = new BuildResult(dictionary3, resultsByTarget3, true, 1, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
        }
Example #7
0
        /// <summary>
        /// Constructor to create a new MSBuild.BuildItem and add it to the project
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        internal ProjectElement(ProjectNode project, string itemPath, string itemType)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (String.IsNullOrEmpty(itemPath))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "itemPath");
            }


            if (String.IsNullOrEmpty(itemType))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "itemType");
            }

            this.itemProject = project;

            // create and add the item to the project

            this.item = project.BuildProject.AddNewItem(itemType, Microsoft.Build.BuildEngine.Utilities.Escape(itemPath));
            this.itemProject.SetProjectFileDirty(true);
            this.RefreshProperties();
        }
Example #8
0
        public void CacheEntryGettersDefaultConstructors()
        {
            BuildItem[] buildItems = new BuildItem[2] { null, null };

            BuildItemCacheEntry tice = new BuildItemCacheEntry();
            Assertion.AssertEquals(null, tice.Name);
            Assertion.AssertEquals(null, tice.BuildItems);
            
            tice.Name = "tice";
            tice.BuildItems = buildItems;
            Assertion.AssertEquals("tice", tice.Name);
            Assertion.AssertEquals(buildItems, tice.BuildItems);

            PropertyCacheEntry pce = new PropertyCacheEntry();
            Assertion.AssertEquals(null, pce.Name);
            Assertion.AssertEquals(null, pce.Value);

            pce.Name = "pce";
            pce.Value = "propertyValue";
            Assertion.AssertEquals("pce", pce.Name);
            Assertion.AssertEquals("propertyValue", pce.Value);

            BuildResultCacheEntry brce = new BuildResultCacheEntry();
            Assertion.AssertEquals(null, brce.Name);
            Assertion.AssertEquals(null, brce.BuildItems);
            Assertion.AssertEquals(default(bool), brce.BuildResult);

            brce.Name = "brce";
            brce.BuildItems = buildItems;
            brce.BuildResult = false;
            Assertion.AssertEquals("brce", brce.Name);
            Assertion.AssertEquals(buildItems, brce.BuildItems);
            Assertion.AssertEquals(false, brce.BuildResult);
        }
Example #9
0
		internal BuildItemGroup (XmlElement xmlElement, Project project, ImportedProject importedProject, bool readOnly, bool dynamic)
		{
			this.buildItems = new List <BuildItem> ();
			this.importedProject = importedProject;
			this.itemGroupElement = xmlElement;
			this.parentProject = project;
			this.read_only = readOnly;
			this.isDynamic = dynamic;
			
			if (!FromXml)
				return;

			foreach (XmlNode xn in xmlElement.ChildNodes) {
				if (!(xn is XmlElement))
					continue;
					
				XmlElement xe = (XmlElement) xn;
				BuildItem bi = new BuildItem (xe, this);
				buildItems.Add (bi);
				project.LastItemGroupContaining [bi.Name] = this;
			}

			DefinedInFileName = importedProject != null ? importedProject.FullFileName :
						project != null ? project.FullFileName : null;
		}
        public void Initialize()
        {
            // Create some items and place them in a dictionary
            // Add some include information so that when we check the final 
            // item spec we can verify that the item was recreated properly
            BuildItem buildItem1 = new BuildItem("BuildItem1", "Item1");
            buildItem1.Include = "TestInclude1";
            BuildItem[] buildItems = new BuildItem[1];
            buildItems[0] = buildItem1;
            Dictionary<object, object> dictionary = new Dictionary<object, object>();
            dictionary.Add("TaskItems", buildItems);

            Hashtable resultByTargetSuccess = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultByTargetSuccess.Add("TaskItems", Target.BuildState.CompletedSuccessfully);
            Hashtable resultByTargetFailure = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultByTargetFailure.Add("TaskItems", Target.BuildState.CompletedUnsuccessfully);
            Hashtable resultByTargetSkipped = new Hashtable(StringComparer.OrdinalIgnoreCase);
            resultByTargetSkipped.Add("TaskItems", Target.BuildState.Skipped);

            resultWithOutputs = new BuildResult(dictionary, resultByTargetSuccess, true, 1, 1, 3, true, string.Empty, string.Empty, 0, 0, 0);
            failedResult = new BuildResult(dictionary, resultByTargetFailure, false, 1, 1, 3, true, string.Empty, string.Empty, 0, 0, 0);
            uncacheableResult = new BuildResult(dictionary, resultByTargetSkipped, true, 1, 1, 3, true, string.Empty, string.Empty, 0, 0, 0);

            cacheScope = new CacheScope("temp.proj", new BuildPropertyGroup(), "3.5");
        }
Example #11
0
 /// <summary>
 /// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from 
 /// a task match the expected set of ITaskItems.  It can also check that the ITaskItems have the expected
 /// metadata, and that the ITaskItems are returned in the correct order.
 /// 
 /// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see.
 /// The format is:
 /// 
 ///         itemspec1 :   metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ...
 ///         itemspec2 :   metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ...
 ///         itemspec3 :   metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ...
 /// 
 /// (Each item needs to be on its own line.)
 /// 
 /// </summary>
 /// <param name="expectedItemsString"></param>
 /// <param name="actualItems"></param>
 /// <owner>RGoel</owner>
 static internal void AssertItemsMatch
     (
     string expectedItemsString, 
     BuildItem[] actualItems
     )
 {
     AssertItemsMatch(expectedItemsString, actualItems, true);
 }
Example #12
0
 public void Basic()
 {
     BuildItem item = new BuildItem("i", "i1");
     Assertion.AssertEquals("i", item.Name);
     Assertion.AssertEquals("i1", item.EvaluatedItemSpec);
     Assertion.AssertEquals("i1", item.FinalItemSpec);
     Assertion.AssertEquals("i1", item.FinalItemSpecEscaped);
 }
		public void AddDependencies(ProjectInfo[] depends)
		{
			foreach (ProjectInfo proj in depends)
			{
				BuildItem bi = new BuildItem("Reference", proj.AssemblyName);
				bi.SetMetadata("SpecificVersion", false.ToString());
				bi.SetMetadata("HintPath", proj.AbsoluteOutputPath);
				_psedoDepends.Add(new ProjectRef(bi, GetProjectPath));
			}
		}
Example #14
0
        /// <summary>
        /// Gets an array containing all custom metadata names.
        /// </summary>
        public static string[] GetCustomMetadataNames(MSBuild.BuildItem item)
        {
            ArrayList a = (ArrayList)typeof(MSBuild.BuildItem).InvokeMember(
                "GetAllCustomMetadataNames",
                BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
                null, item, null
                );

            return((string[])a.ToArray(typeof(string)));
        }
 private string GetReferenceDllName(BuildItem item)
 {
     string spec = item.FinalItemSpec;
     int commaIndex = spec.IndexOf(CHAR_Comma);
     if (commaIndex >= 0)
     {
         return spec.Substring(0, commaIndex);
     }
     return spec;
 }
Example #16
0
 /// <summary>
 /// Calling this method remove this item from the project file.
 /// Once the item is delete, you should not longer be using it.
 /// Note that the item should be removed from the hierarchy prior to this call.
 /// </summary>
 public void RemoveFromProjectFile()
 {
     if (!deleted && item != null)
     {
         deleted = true;
         itemProject.BuildProject.RemoveItem(item);
     }
     itemProject = null;
     item        = null;
 }
Example #17
0
        public void RemoveItem(BuildItem itemToRemove)
        {
            if (itemToRemove == null)
            {
                return;
            }

            itemToRemove.Detach();

            buildItems.Remove(itemToRemove);
        }
Example #18
0
 /// <summary>
 /// If this is a persisted group, removes the XML element corresponding to the given item.
 /// If this is not a persisted group, does nothing.
 /// </summary>
 private void RemoveItemElement(BuildItem item)
 {
     if (IsPersisted)
     {
         MustNotBeImported();
         MustHaveThisParentElement(item);
         MustHaveThisParentGroup(item);
         xml.Element.RemoveChild(item.ItemElement);
         item.ParentPersistedItemGroup = null;
     }
 }
Example #19
0
        void AddEvaluatedItem(Project project, bool evaluatedTo, ITaskItem taskitem)
        {
            if (IsDynamic && evaluatedTo && !KeepDuplicates && ContainsItem(project, taskitem))
            {
                return;
            }

            BuildItemGroup big;
            BuildItem      bi = new BuildItem(this);

            bi.finalItemSpec = ((ITaskItem2)taskitem).EvaluatedIncludeEscaped;

            foreach (DictionaryEntry de in taskitem.CloneCustomMetadata())
            {
                bi.unevaluatedMetadata.Add((string)de.Key, (string)de.Value);
                bi.evaluatedMetadata.Add((string)de.Key, (string)de.Value);
            }

            project.EvaluatedItemsIgnoringCondition.AddItem(bi);

            if (evaluatedTo)
            {
                project.EvaluatedItems.AddItem(bi);

                if (!project.EvaluatedItemsByName.ContainsKey(bi.Name))
                {
                    big = new BuildItemGroup(null, project, null, true);
                    project.EvaluatedItemsByName.Add(bi.Name, big);
                }
                else
                {
                    big = project.EvaluatedItemsByName [bi.Name];
                }

                big.AddItem(bi);
            }

            if (!project.EvaluatedItemsByNameIgnoringCondition.ContainsKey(bi.Name))
            {
                big = new BuildItemGroup(null, project, null, true);
                project.EvaluatedItemsByNameIgnoringCondition.Add(bi.Name, big);
            }
            else
            {
                big = project.EvaluatedItemsByNameIgnoringCondition [bi.Name];
            }

            big.AddItem(bi);

            if (IsDynamic)
            {
                AddAndRemoveMetadata(project, bi);
            }
        }
Example #20
0
        /// <summary>
        /// Gets all custom metadata names defined directly on the item, ignoring defaulted metadata entries.
        /// </summary>
        public static IList <string> GetCustomMetadataNames(MSBuild.BuildItem item)
        {
            PropertyInfo prop     = typeof(MSBuild.BuildItem).GetProperty("ItemDefinitionLibrary", BindingFlags.Instance | BindingFlags.NonPublic);
            object       oldValue = prop.GetValue(item, null);

            prop.SetValue(item, null, null);
            IList <string> result = (IList <string>)item.CustomMetadataNames;

            prop.SetValue(item, oldValue, null);
            return(result);
        }
 private string GetAssemblyPathFromVSInstalDir(BuildItem item)
 {
     string name = GetReferenceDllName(item);
     string[] installDirs = FrameworkHelper.GetVSInstallFoldersPaths();
     string path = FrameworkHelper.GetAssemblyPath(name, installDirs);
     if (File.Exists(path))
     {
         return path;
     }
     return string.Empty;
 }
Example #22
0
        /// <summary>
        /// Puts the item into the table.
        /// </summary>
        private void ImportItemIntoTable(Hashtable table, BuildItem item)
        {
            BuildItemGroup existing = (BuildItemGroup)table[item.Name];

            if (existing == null)
            {
                existing = new BuildItemGroup();
                table.Add(item.Name, existing);
            }
            existing.AddItem(item);
        }
Example #23
0
        /// <summary>
        /// Constructor to create a new MSBuild.BuildItem and add it to the project
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        internal ProjectElement(ProjectNode project, string itemPath, string itemType)
        {
            if (project == null)
                throw new ArgumentNullException("project", String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.AddToNullProjectError), itemPath));

            itemProject = project;

            // create and add the item to the project
            item = project.BuildProject.AddNewItem(itemType, itemPath);
            project.SetProjectFileDirty(true);
            this.RefreshProperties();
        }
Example #24
0
        public void CopyCustomMetadataTo(BuildItem destinationItem)
        {
            if (destinationItem == null)
            {
                throw new ArgumentNullException("destinationItem");
            }

            foreach (DictionaryEntry de in unevaluatedMetadata)
            {
                destinationItem.AddMetadata((string)de.Key, (string)de.Value);
            }
        }
Example #25
0
        /// <summary>
        /// Copy constructor
        /// </summary>
        internal BuildResult
            (BuildResult buildResultToCopy, bool deepCopy)
        {
            ErrorUtilities.VerifyThrowArgumentNull(buildResultToCopy, "Cannot have a null build result passed in");
            this.flags = buildResultToCopy.flags;
            this.handleId = buildResultToCopy.handleId;
            this.requestId = buildResultToCopy.requestId;
            this.projectId = buildResultToCopy.projectId;
            this.outputsByTarget = new Hashtable();
            this.defaultTargets = buildResultToCopy.defaultTargets;
            this.initialTargets = buildResultToCopy.initialTargets;
            this.resultByTarget = new Hashtable(buildResultToCopy.resultByTarget, StringComparer.OrdinalIgnoreCase);

            if (buildResultToCopy.outputsByTarget == null)
            {
                return;
            }

            if (deepCopy)
            {
                // Copy all the old data
                foreach (DictionaryEntry entry in buildResultToCopy.outputsByTarget)
                {
                    // Make deep copies of all the target outputs before
                    // passing them back
                    BuildItem[] originalArray = (BuildItem[])entry.Value;
                    BuildItem[] itemArray = new BuildItem[originalArray.Length];
                    for (int i = 0; i < originalArray.Length; i++)
                    {
                        if (!originalArray[i].IsUninitializedItem)
                        {
                            itemArray[i] = originalArray[i].Clone();
                            itemArray[i].CloneVirtualMetadata();
                        }
                        else
                        {
                            itemArray[i] = new BuildItem(null, originalArray[i].FinalItemSpecEscaped);
                        }
                    }
                    
                    this.outputsByTarget.Add(entry.Key, itemArray);
                }
            }
            else
            {
                // Create a new hashtable but point at the same data
                foreach (DictionaryEntry entry in buildResultToCopy.outputsByTarget)
                {
                    this.outputsByTarget.Add(entry.Key, entry.Value);
                }
            }
        }
Example #26
0
        /// <summary>
        /// Copy constructor
        /// </summary>
        internal BuildResult
            (BuildResult buildResultToCopy, bool deepCopy)
        {
            ErrorUtilities.VerifyThrowArgumentNull(buildResultToCopy, "Cannot have a null build result passed in");
            this.flags           = buildResultToCopy.flags;
            this.handleId        = buildResultToCopy.handleId;
            this.requestId       = buildResultToCopy.requestId;
            this.projectId       = buildResultToCopy.projectId;
            this.outputsByTarget = new Hashtable();
            this.defaultTargets  = buildResultToCopy.defaultTargets;
            this.initialTargets  = buildResultToCopy.initialTargets;
            this.resultByTarget  = new Hashtable(buildResultToCopy.resultByTarget, StringComparer.OrdinalIgnoreCase);

            if (buildResultToCopy.outputsByTarget == null)
            {
                return;
            }

            if (deepCopy)
            {
                // Copy all the old data
                foreach (DictionaryEntry entry in buildResultToCopy.outputsByTarget)
                {
                    // Make deep copies of all the target outputs before
                    // passing them back
                    BuildItem[] originalArray = (BuildItem[])entry.Value;
                    BuildItem[] itemArray     = new BuildItem[originalArray.Length];
                    for (int i = 0; i < originalArray.Length; i++)
                    {
                        if (!originalArray[i].IsUninitializedItem)
                        {
                            itemArray[i] = originalArray[i].Clone();
                            itemArray[i].CloneVirtualMetadata();
                        }
                        else
                        {
                            itemArray[i] = new BuildItem(null, originalArray[i].FinalItemSpecEscaped);
                        }
                    }

                    this.outputsByTarget.Add(entry.Key, itemArray);
                }
            }
            else
            {
                // Create a new hashtable but point at the same data
                foreach (DictionaryEntry entry in buildResultToCopy.outputsByTarget)
                {
                    this.outputsByTarget.Add(entry.Key, entry.Value);
                }
            }
        }
        /// <summary>
        /// Constructor to create a new MSBuild.BuildItem and add it to the project
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        internal ProjectElement(ProjectNode project, string itemPath, string itemType)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project", String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.AddToNullProjectError), itemPath));
            }

            itemProject = project;

            // create and add the item to the project
            item = project.BuildProject.AddNewItem(itemType, itemPath);
            project.SetProjectFileDirty(true);
            this.RefreshProperties();
        }
Example #28
0
        /// <summary>
        /// Look up the "real" item by using its clone, and return the real item.
        /// See <see cref="cloneTable"/> for explanation of the clone table.
        /// </summary>
        private BuildItem RetrieveOriginalFromCloneTable(BuildItem item)
        {
            BuildItem original;

            if (cloneTable != null)
            {
                if (cloneTable.TryGetValue(item, out original))
                {
                    item = original;
                }
            }

            return(item);
        }
Example #29
0
		public void TestCtor1 ()
		{
			string itemName = "itemName";
			string itemInclude = "a;b;c";
	
			item = new BuildItem (itemName, itemInclude);
	
			Assert.AreEqual (itemInclude, item.FinalItemSpec, "A1");
			Assert.AreEqual (itemInclude, item.Include, "A2");
			Assert.AreEqual (String.Empty, item.Exclude, "A3");
			Assert.AreEqual (String.Empty, item.Condition, "A4");
			Assert.AreEqual (false, item.IsImported, "A5");
			Assert.AreEqual (itemName, item.Name, "A6");
		}
Example #30
0
        /// <summary>
        /// Modifies items in this scope with the same set of metadata modifications.
        /// Assumes all the items in the group have the same, provided, type.
        /// </summary>
        internal void ModifyItems(string name, BuildItemGroup group, Dictionary <string, string> metadataChanges)
        {
            MustBeOwningThread();

            // Modifying in outer scope could be easily implemented, but our code does not do it at present
            MustNotBeOuterScope();

#if DEBUG
            // This item should not already be in any remove table; there is no way a project can
            // modify items that were already removed
            // Obviously, do this only in debug, as it's a slow check for bugs.
            LinkedListNode <LookupEntry> node = lookupEntries.First;
            while (node != null)
            {
                LookupEntry entry = node.Value;
                foreach (BuildItem item in group)
                {
                    BuildItem actualItem = RetrieveOriginalFromCloneTable(item);
                    MustNotBeInTable(entry.Removes, actualItem);
                }
                node = node.Next;
            }
#endif

            if (metadataChanges.Count == 0)
            {
                return;
            }

            // Put in the modify table

            // We don't need to check whether the item is in the add table vs. the main table; either
            // way the modification will be applied.
            PrimaryModifyTable = CreateTableIfNecessary(PrimaryModifyTable);
            Dictionary <BuildItem, Dictionary <string, string> > modifiesOfType;
            if (!PrimaryModifyTable.TryGetValue(name, out modifiesOfType))
            {
                modifiesOfType           = new Dictionary <BuildItem, Dictionary <string, string> >();
                PrimaryModifyTable[name] = modifiesOfType;
            }

            foreach (BuildItem item in group)
            {
                // If we're asked to modify a clone we handed out, record it as a modify of the original
                // instead
                BuildItem actualItem = RetrieveOriginalFromCloneTable(item);
                KeyValuePair <BuildItem, Dictionary <string, string> > modify = new KeyValuePair <BuildItem, Dictionary <string, string> >(actualItem, metadataChanges);
                MergeModificationsIntoModificationTable(modifiesOfType, modify, ModifyMergeType.SecondWins);
            }
        }
Example #31
0
        void SplitParentItem()
        {
            BuildItem        parent      = parent_item;
            List <BuildItem> list        = new List <BuildItem> ();
            XmlElement       insertAfter = parent.itemElement;

            foreach (BuildItem bi in parent.child_items)
            {
                BuildItem added = InsertElementAfter(parent, bi, insertAfter);
                insertAfter = added.itemElement;
                list.Add(added);
            }
            parent.parent_item_group.ReplaceWith(parent, list);
            parent.itemElement.ParentNode.RemoveChild(parent.itemElement);
        }
Example #32
0
 /// <summary>
 /// BuildItems are passed around internally, including across the wire. Before passing these
 /// to tasks, they need to be converted into TaskItems using this method.
 /// </summary>
 internal void ConvertToTaskItems()
 {
     // If outputsByTarget was null then we dont have to re-create anything as nothing was passed over
     if (null != outputsByTarget)
     {
         string[] keys = new string[outputsByTarget.Count];
         outputsByTarget.Keys.CopyTo(keys, 0);
         for (int key_index = 0; key_index < keys.Length; key_index++)
         {
             object      key           = keys[key_index];
             BuildItem[] originalArray = (BuildItem[])outputsByTarget[key];
             outputsByTarget[key] = BuildItem.ConvertBuildItemArrayToTaskItems(originalArray);
         }
     }
 }
Example #33
0
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        /// <param name="project">Project that owns this item</param>
        /// <param name="existingItem">an MSBuild.BuildItem; can be null if virtualFolder is true</param>
        /// <param name="virtualFolder">Is this item virtual (such as reference folder)</param>
        internal ProjectElement(ProjectNode project, MSBuild.BuildItem existingItem, bool virtualFolder)
        {
            if (project == null)
                throw new ArgumentNullException("project", String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.AddToNullProjectError), existingItem.Include));
            if (!virtualFolder && existingItem == null)
                throw new ArgumentNullException("existingItem");

            // Keep a reference to project and item
            itemProject = project;
            item = existingItem;
            isVirtual = virtualFolder;

            if (isVirtual)
                virtualProperties = new Dictionary<string, string>();
        }
Example #34
0
		private void FromFileReference(BuildItem bi, TranslatePath fnTranslate)
		{
			if (!String.IsNullOrEmpty(bi.Include))
			{
				this.Assembly = new AssemblyName(bi.Include);
				SpecificVersion |= this.Assembly.Version != null;
			}
			if (!String.IsNullOrEmpty(bi.GetMetadata("HintPath")))
			{
				string path = bi.GetMetadata("HintPath");
				fnTranslate(ref path);//< output file doesn't nessessarily exist
				this.Output = path;
			}
			this.RequiresVersion = bi.GetMetadata("RequiredTargetFramework");
		}
Example #35
0
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        /// <param name="project">Project that owns this item</param>
        /// <param name="existingItem">an MSBuild.BuildItem; can be null if virtualFolder is true</param>
        /// <param name="virtualFolder">Is this item virtual (such as reference folder)</param>
        internal ProjectElement(ProjectNode project, MSBuild.BuildItem existingItem, bool virtualFolder)
        {
            if(project == null)
                throw new ArgumentNullException("project");
            if(!virtualFolder && existingItem == null)
                throw new ArgumentNullException("existingItem");

            // Keep a reference to project and item
            this.itemProject = project;
            this.item = existingItem;
            this.isVirtual = virtualFolder;

            if(this.isVirtual)
                this.virtualProperties = new Dictionary<string, string>();
        }
Example #36
0
        /// <summary>
        /// Create a secret backup list of our persisted items only.
        /// Then, we can revert back to this later when we're done with the build,
        /// and we want to remove any virtual items and revert any removes of
        /// persisted items.
        /// </summary>
        internal void BackupPersistedItems()
        {
            if (!IsBackedUp)
            {
                persistedItemBackup = new List <BuildItem>();

                foreach (BuildItem item in items)
                {
                    if (item.IsPartOfProjectManifest)
                    {
                        BuildItem itemClone = item.Clone();
                        persistedItemBackup.Add(itemClone);
                    }
                }
            }
        }
Example #37
0
        /// <summary>
        /// Verify item is not in any table in any scope
        /// </summary>
        private void MustNotBeInAnyTables(BuildItem item)
        {
            // This item should not already be in any table; there is no way a project can
            // create items that already existed
            // Obviously, do this only in debug, as it's a slow check for bugs.
            LinkedListNode <LookupEntry> node = lookupEntries.First;

            while (node != null)
            {
                LookupEntry entry = node.Value;
                MustNotBeInTable(entry.Adds, item);
                MustNotBeInTable(entry.Removes, item);
                MustNotBeInTable(entry.Modifies, item);
                node = node.Next;
            }
        }
Example #38
0
		public ProjectRef(BuildItem item, TranslatePath fnTranslate)
		{
			this.RefType = String.Format("{0}", Check.NotNull(item).Name);
			if (item.GetMetadata("Private") == "True")
				CopyLocal = true;
			if (item.GetMetadata("SpecificVersion") == "True")
				SpecificVersion = true;
			if (!String.IsNullOrEmpty(item.Condition))
				this.Condition = item.Condition;
			if (RefType == "ProjectReference")
				this.FromProjectReference(item, Check.NotNull(fnTranslate));
			else if (RefType == "Reference")
				this.FromFileReference(item, Check.NotNull(fnTranslate));
			else
				throw new ApplicationException("Unkown reference type " + RefType);
		}
Example #39
0
        /// <summary>
        /// Removes the given BuildItem from this BuildItemGroup.
        /// If the item is part of the project manifest (ie, it's declared outside of a target) then
        /// makes a backup of persisted items so that later the item group can be reverted to that backup,
        /// reversing this change.
        /// </summary>
        internal void RemoveItemWithBackup(BuildItem itemToRemove)
        {
            MustBeInitialized();

            if (itemToRemove.IsPartOfProjectManifest)
            {
                // We're about to remove an item that's part of the project manifest;
                // this must be reverted when we reset the project, so make sure we've got a backup
                BackupPersistedItems();
            }

            // Don't remove the XML node, or mark the itemgroup as dirty; this is
            // strictly an operation on temporary items, because we'll be un-backing up the
            // persisted items at the end of the build

            items.Remove(itemToRemove);
        }
Example #40
0
        /// <summary>
        /// Remove an item from this scope
        /// </summary>
        internal void RemoveItem(BuildItem item)
        {
            MustBeOwningThread();

            // Removing from outer scope could be easily implemented, but our code does not do it at present
            MustNotBeOuterScope();

            item = RetrieveOriginalFromCloneTable(item);

            // Put in the remove table
            PrimaryRemoveTable = Utilities.CreateTableIfNecessary(PrimaryRemoveTable);
            ImportItemIntoTable(PrimaryRemoveTable, item);

            // No need to remove this item from the primary add table if it's
            // already there -- we always apply removes after adds, so that add
            // will be reversed anyway.
        }
Example #41
0
        /// <summary>
        /// Reevaluate all properties for the current item
        /// This should be call if you believe the property for this item
        /// may have changed since it was created/refreshed, or global properties
        /// this items depends on have changed.
        /// Be aware that there is a perf cost in calling this function.
        /// </summary>
        public void RefreshProperties()
        {
            if (this.IsVirtual)
            {
                return;
            }

            MSBuild.BuildItemGroup items = itemProject.BuildProject.EvaluatedItems;
            foreach (MSBuild.BuildItem projectItem in items)
            {
                if (projectItem.Include == item.Include)
                {
                    item = projectItem;
                    return;
                }
            }
        }
Example #42
0
		public void TestCtor2 ()
		{
			string itemName = "itemName";
			string itemSpec = "a;b;c";
			// result of Utilities.Escape (itemSpec)
			string escapedInclude = "a%3bb%3bc";
			ITaskItem taskItem = new TaskItem (itemSpec);

			item = new BuildItem (itemName, taskItem);
	
			Assert.AreEqual (itemSpec, item.FinalItemSpec, "A1");
			Assert.AreEqual (escapedInclude, item.Include, "A2");
			Assert.AreEqual (String.Empty, item.Exclude, "A3");
			Assert.AreEqual (String.Empty, item.Condition, "A4");
			Assert.AreEqual (false, item.IsImported, "A5");
			Assert.AreEqual (itemName, item.Name, "A6");
		}
Example #43
0
        public void CacheEntryGetters()
        {
            BuildItem[] buildItems = new BuildItem[2] { null, null };

            BuildItemCacheEntry tice = new BuildItemCacheEntry("tice", buildItems);
            Assertion.AssertEquals("tice", tice.Name);
            Assertion.AssertEquals(buildItems, tice.BuildItems);

            PropertyCacheEntry pce = new PropertyCacheEntry("pce", "propertyValue");
            Assertion.AssertEquals("pce", pce.Name);
            Assertion.AssertEquals("propertyValue", pce.Value);

            BuildResultCacheEntry brce = new BuildResultCacheEntry("brce", buildItems, true);
            Assertion.AssertEquals("brce", brce.Name);
            Assertion.AssertEquals(buildItems, brce.BuildItems);
            Assertion.AssertEquals(true, brce.BuildResult);
        }
Example #44
0
        public void Initialize()
        {
            // Create some items and place them in a dictionary
            // Add some include information so that when we check the final 
            // item spec we can verify that the item was recreated properly
            buildItem1.Include = "TestInclude1";
            buildItem2.Include = "TestInclude2";

            BuildItem[] taskItems = new BuildItem[2];
            taskItems[0] = buildItem1;
            taskItems[1] = buildItem2;

            Dictionary<object, object> dictionary = new Dictionary<object, object>();
            dictionary.Add("TaskItems", taskItems);
            resultNoOutputs = new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), true, 0, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
            resultWithOutputs = new BuildResult(dictionary, new Hashtable(StringComparer.OrdinalIgnoreCase), true, 0, 1, 2, true, string.Empty, string.Empty, 0, 0, 0);
        }
Example #45
0
        /// <summary>
        /// Creates a new BuildItem defined by the given "Type" and "Include", and
        /// adds it to the end of this BuildItemGroup.
        /// If the group is persisted, the item is persisted; otherwise it is virtual
        /// </summary>
        public BuildItem AddNewItem(string itemName, string itemInclude)
        {
            BuildItem newItem;

            if (IsPersisted)
            {
                // We are a persisted <ItemGroup>, so create a new persisted item object.
                newItem = new BuildItem(xml.OwnerDocument, itemName, itemInclude, parentProject.ItemDefinitionLibrary);
            }
            else
            {
                // Create a new virtual BuildItem.
                newItem = new BuildItem(itemName, itemInclude);
            }

            AddItem(newItem);
            return(newItem);
        }
Example #46
0
        /// <summary>
        /// Applies each of the item modifications in order.
        /// Items are replaced with a virtual clone before they are modified.
        /// If an item does not exist in this group, the modification is skipped.
        /// If any modifications conflict, these modifications win.
        /// Returns the cloned item made, or null if it does not exist in this group.
        /// </summary>
        internal BuildItem ModifyItemAfterCloningUsingVirtualMetadata(BuildItem item, Dictionary<string, string> metadata)
        {
            int index = items.IndexOf(item);
            if (index > -1)
            {
                BuildItem clone = items[index].VirtualClone();
                items[index] = clone;

                foreach (KeyValuePair<string, string> pair in metadata)
                {
                    clone.SetVirtualMetadata(pair.Key, pair.Value);
                }

                return clone;
            }

            return null;
        }
Example #47
0
        void AddEvaluatedItem(Project project, bool evaluatedTo, ITaskItem taskitem)
        {
            BuildItemGroup big;
            BuildItem      bi = new BuildItem(this);

            bi.finalItemSpec = taskitem.ItemSpec;

            foreach (DictionaryEntry de in taskitem.CloneCustomMetadata())
            {
                bi.unevaluatedMetadata.Add((string)de.Key, (string)de.Value);
                bi.evaluatedMetadata.Add((string)de.Key, (string)de.Value);
            }

            project.EvaluatedItemsIgnoringCondition.AddItem(bi);

            if (evaluatedTo)
            {
                project.EvaluatedItems.AddItem(bi);

                if (!project.EvaluatedItemsByName.ContainsKey(bi.Name))
                {
                    big = new BuildItemGroup(null, project, null, true);
                    project.EvaluatedItemsByName.Add(bi.Name, big);
                }
                else
                {
                    big = project.EvaluatedItemsByName [bi.Name];
                }

                big.AddItem(bi);
            }

            if (!project.EvaluatedItemsByNameIgnoringCondition.ContainsKey(bi.Name))
            {
                big = new BuildItemGroup(null, project, null, true);
                project.EvaluatedItemsByNameIgnoringCondition.Add(bi.Name, big);
            }
            else
            {
                big = project.EvaluatedItemsByNameIgnoringCondition [bi.Name];
            }

            big.AddItem(bi);
        }
Example #48
0
		public ReferenceInfo(Project project, BuildItem item)
		{
            _project = project;
            _item = item;
            _refType = (ReferenceType)Enum.Parse(typeof(ReferenceType), item.Name);

			if (_refType == ReferenceType.ProjectReference)
            {
				_assembly = new AssemblyName();
            }
            else if (RefType == ReferenceType.Reference)
            {
				string name = _item.Include;
				if (name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
					name = name.Substring(0, name.Length - 4);
				_assembly = new AssemblyName(name);
            }
            else
                throw new ApplicationException("Unkown reference type " + item.Name);
		}
Example #49
0
 internal override void CreateFromStream(BinaryReader reader)
 {
     base.CreateFromStream(reader);
     buildItems = null;
     if (reader.ReadByte() != 0)
     {
         int sizeOfArray = reader.ReadInt32();
         buildItems = new BuildItem[sizeOfArray];
         for (int j = 0; j < sizeOfArray; j++)
         {
             BuildItem itemToAdd = null;
             if (reader.ReadByte() != 0)
             {
                 itemToAdd = new BuildItem(null, string.Empty);
                 itemToAdd.CreateFromStream(reader);
             }
             buildItems[j] = itemToAdd;
         }
     }
 }
Example #50
0
        /// <summary>
        /// Implements a true add, an item that has been created in a batch.
        /// </summary>
        internal void AddNewItem(BuildItem item)
        {
            MustBeOwningThread();
            // We only expect to add virtual items during the build
            ErrorUtilities.VerifyThrow(!item.IsPartOfProjectManifest, "Cannot dynamically add manifest items");

            // Adding to outer scope could be easily implemented, but our code does not do it at present
            MustNotBeOuterScope();

#if DEBUG
            // This item must not be in any table already; a project cannot create an item
            // that already exists
            MustNotBeInAnyTables(item);
#endif
            item.ItemDefinitionLibrary = this.itemDefinitionLibrary;

            // Put in the add table
            PrimaryAddTable = Utilities.CreateTableIfNecessary(PrimaryAddTable);
            ImportItemIntoTable(PrimaryAddTable, item);
        }
Example #51
0
        /// <summary>
        /// Adds an existing BuildItem to the list of items at the specified index.
        /// Does not attempt to add backing Xml for the item.
        /// </summary>
        internal void AddExistingItemAt(int index, BuildItem itemToAdd)
        {
            ErrorUtilities.VerifyThrow(items != null, "BuildItemGroup has not been initialized.");
            ErrorUtilities.VerifyThrow(index <= items.Count, "Index out of range");

            items.Insert(index, itemToAdd);

            if (parentProject != null)
            {
                itemToAdd.ItemDefinitionLibrary = parentProject.ItemDefinitionLibrary;
            }

            // If this BuildItemGroup is a persisted <ItemGroup>, then we need the
            // items to have a reference back to their parent BuildItemGroup.  This
            // makes it *much* easier to delete items through the object model.
            if (IsPersisted)
            {
                itemToAdd.ParentPersistedItemGroup = this;
            }
            MarkItemGroupAsDirty();
        }
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        /// <param name="project">Project that owns this item</param>
        /// <param name="existingItem">an MSBuild.BuildItem; can be null if virtualFolder is true</param>
        /// <param name="virtualFolder">Is this item virtual (such as reference folder)</param>
        internal ProjectElement(ProjectNode project, MSBuild.BuildItem existingItem, bool virtualFolder)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project", String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.AddToNullProjectError), existingItem.Include));
            }
            if (!virtualFolder && existingItem == null)
            {
                throw new ArgumentNullException("existingItem");
            }

            // Keep a reference to project and item
            itemProject = project;
            item        = existingItem;
            isVirtual   = virtualFolder;

            if (isVirtual)
            {
                virtualProperties = new Dictionary <string, string>();
            }
        }
Example #53
0
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        /// <param name="project">Project that owns this item</param>
        /// <param name="existingItem">an MSBuild.BuildItem; can be null if virtualFolder is true</param>
        /// <param name="virtualFolder">Is this item virtual (such as reference folder)</param>
        internal ProjectElement(ProjectNode project, MSBuild.BuildItem existingItem, bool virtualFolder)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (!virtualFolder && existingItem == null)
            {
                throw new ArgumentNullException("existingItem");
            }

            // Keep a reference to project and item
            this.itemProject = project;
            this.item        = existingItem;
            this.isVirtual   = virtualFolder;

            if (this.isVirtual)
            {
                this.virtualProperties = new Dictionary <string, string>();
            }
        }
        /// <summary>
        /// Does the actual job of resolving an assembly reference. We need a private method that does not violate
        /// calling virtual method from the constructor.
        /// </summary>
        private void ResolveAssemblyReference()
        {
            if (this.ProjectMgr == null || this.ProjectMgr.IsClosed || !this.ProjectMgr.HasPassedSecurityChecks)
            {
                return;
            }

            MSBuild.BuildItemGroup group = this.ProjectMgr.BuildProject.GetEvaluatedItemsByName(ProjectFileConstants.ReferencePath);
            if (group != null)
            {
                IEnumerator enumerator = group.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    MSBuild.BuildItem item = (MSBuild.BuildItem)enumerator.Current;

                    string fullPath = this.GetFullPathFromPath(item.FinalItemSpec);

                    System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(fullPath);

                    // Try with full assembly name and then with weak assembly name.
                    if (String.Compare(name.FullName, this.assemblyName.FullName, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(name.Name, this.assemblyName.Name, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (!NativeMethods.IsSamePath(fullPath, this.assemblyPath))
                        {
                            // set the full path now.
                            this.assemblyPath = fullPath;

                            // We have a new item to listen too, since the assembly reference is resolved from a different place.
                            this.fileChangeListener.ObserveItem(this.assemblyPath);
                        }

                        this.resolvedAssemblyName = name;

                        // No hint path is needed since the assembly path will always be resolved.
                        return;
                    }
                }
            }
        }
        public void CantModifyThroughEnumerator()
        {
            BuildItemGroup ig = new BuildItemGroup();
            BuildItem i1 = new BuildItem("name1", "value1");
            i1.SetMetadata("myMetaName", "myMetaValue");
            ig.AddItem(i1);

            BuildItemGroupProxy proxy = new BuildItemGroupProxy(ig);

            Hashtable list = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach (DictionaryEntry item in proxy)
            {
                list.Add(item.Key, item.Value);
            }

            // Change the item
            Assertion.AssertEquals("value1", ((TaskItem)list["name1"]).ItemSpec);
            ((TaskItem)list["name1"]).ItemSpec = "newItemSpec";
            ((TaskItem)list["name1"]).SetMetadata("newMetadata", "newMetadataValue");

            // We did change our copy
            Assertion.AssertEquals("newItemSpec", ((TaskItem)list["name1"]).ItemSpec);
            Assertion.AssertEquals("newMetadataValue", ((TaskItem)list["name1"]).GetMetadata("newMetadata"));
            Assertion.AssertEquals("myMetaValue", ((TaskItem)list["name1"]).GetMetadata("myMetaName"));

            // But get the item again
            list = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach (DictionaryEntry item in proxy)
            {
                list.Add(item.Key, item.Value);
            }

            // Item value and metadata hasn't changed
            Assertion.AssertEquals("value1", ((TaskItem)list["name1"]).ItemSpec);
            Assertion.AssertEquals("", ((TaskItem)list["name1"]).GetMetadata("newMetadata"));
            Assertion.AssertEquals("myMetaValue", ((TaskItem)list["name1"]).GetMetadata("myMetaName"));
        }
Example #56
0
		static BuildItem InsertElementAfter (BuildItem parent, BuildItem child, XmlElement insertAfter)
		{
			BuildItem newParent;

			XmlDocument doc = parent.itemElement.OwnerDocument;
			XmlElement newElement = doc.CreateElement (child.Name, Project.XmlNamespace);
			newElement.SetAttribute ("Include", child.FinalItemSpec);
			if (parent.itemElement.HasAttribute ("Condition"))
				newElement.SetAttribute ("Condition", parent.itemElement.GetAttribute ("Condition"));
			foreach (XmlNode xn in parent.itemElement)
				newElement.AppendChild (xn.Clone ());
			parent.itemElement.ParentNode.InsertAfter (newElement, insertAfter);

			newParent = new BuildItem (newElement, parent.parent_item_group);
			newParent.child_items.Add (child);
			child.parent_item = newParent;

			return newParent;
		}
Example #57
0
		void AddEvaluatedItem (Project project, bool evaluatedTo, ITaskItem taskitem)
		{
			if (IsDynamic && evaluatedTo && !KeepDuplicates && ContainsItem (project, taskitem))
				return;

			BuildItemGroup big;			
			BuildItem bi = new BuildItem (this);
			bi.finalItemSpec = taskitem.ItemSpec;

			foreach (DictionaryEntry de in taskitem.CloneCustomMetadata ()) {
				bi.unevaluatedMetadata.Add ((string) de.Key, (string) de.Value);
				bi.evaluatedMetadata.Add ((string) de.Key, (string) de.Value);
			}

			project.EvaluatedItemsIgnoringCondition.AddItem (bi);

			if (evaluatedTo) {
				project.EvaluatedItems.AddItem (bi);
	
				if (!project.EvaluatedItemsByName.ContainsKey (bi.Name)) {
					big = new BuildItemGroup (null, project, null, true);
					project.EvaluatedItemsByName.Add (bi.Name, big);
				} else {
					big = project.EvaluatedItemsByName [bi.Name];
				}

				big.AddItem (bi);
			}

			if (!project.EvaluatedItemsByNameIgnoringCondition.ContainsKey (bi.Name)) {
				big = new BuildItemGroup (null, project, null, true);
				project.EvaluatedItemsByNameIgnoringCondition.Add (bi.Name, big);
			} else {
				big = project.EvaluatedItemsByNameIgnoringCondition [bi.Name];
			}

			big.AddItem (bi);

			if (IsDynamic)
				AddAndRemoveMetadata (project, bi);
		}
Example #58
0
		void AddAndRemoveMetadata (Project project, BuildItem item)
		{
			if (!string.IsNullOrEmpty (removeMetadata)) {
				var removeExpr = new Expression ();
				removeExpr.Parse (removeMetadata, ParseOptions.AllowItemsNoMetadataAndSplit);

				var removeSpec = (string[]) removeExpr.ConvertTo (
					project, typeof (string[]), ExpressionOptions.ExpandItemRefs);

				foreach (var remove in removeSpec) {
					item.DeleteMetadata (remove);
				}
			}

			if (!string.IsNullOrEmpty (keepMetadata)) {
				var keepExpr = new Expression ();
				keepExpr.Parse (keepMetadata, ParseOptions.AllowItemsNoMetadataAndSplit);

				var keepSpec = (string[]) keepExpr.ConvertTo (
					project, typeof (string[]), ExpressionOptions.ExpandItemRefs);

				var metadataNames = new string [item.evaluatedMetadata.Count];
				item.evaluatedMetadata.Keys.CopyTo (metadataNames, 0);

				foreach (string name in metadataNames) {
					if (!keepSpec.Contains (name))
						item.DeleteMetadata (name);
				}
			}
		}
Example #59
0
		public void CopyCustomMetadataTo (BuildItem destinationItem)
		{
			if (destinationItem == null)
				throw new ArgumentNullException ("destinationItem");

			foreach (DictionaryEntry de in unevaluatedMetadata)
				destinationItem.AddMetadata ((string) de.Key, (string) de.Value);
		}
Example #60
0
		BuildItem (BuildItem parent)
		{
			isImported = parent.isImported;
			name = parent.Name;
			parent_item = parent;
			parent_item.child_items.Add (this);
			parent_item_group = parent.parent_item_group;
			unevaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable (parent.unevaluatedMetadata);
			evaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable (parent.evaluatedMetadata);
		}