private static void TrySetHintPath(VSLangProj80.Reference3 reference)
        {
            try
            {
                Microsoft.Build.Evaluation.Project project =
                    MSBuildUtils.LoadedProject(reference.ContainingProject.FullName, false, false);

                Microsoft.Build.Evaluation.ProjectItem item =
                    project.AllEvaluatedItems.FirstOrDefault(i =>
                                                             i.ItemType.Equals("Reference") &&
                                                             i.EvaluatedInclude.Split(",".ToCharArray()).ElementAt(0).Equals(reference.Name)
                                                             );
                if (item != null)
                {
                    item.SetMetadataValue("HintPath", Path.Combine("$(IceAssembliesDir)",
                                                                   string.Format("{0}.dll", reference.Name)));
                }
            }
            catch (NotSupportedException)
            {
            }
            catch (NotImplementedException)
            {
            }
            catch (COMException)
            {
            }
        }
        protected ProjectItem(
            IProject project,
            Microsoft.Build.Evaluation.ProjectItem msBuildProjectItem)
        {
            Project             = project;
            OriginalProjectItem = msBuildProjectItem;

            Include = new ProjectItemInclude(msBuildProjectItem.EvaluatedInclude, msBuildProjectItem.UnevaluatedInclude);

            BuildAction = ProjectItemBuildAction.Custom(msBuildProjectItem.ItemType);
            var fullPath = Path.GetFullPath(Path.Combine(project.ProjectFile.DirectoryName, msBuildProjectItem.EvaluatedInclude));

            File = Wrapper.Wrap(new FileInfo(fullPath));

            Location = new ProjectLocation(msBuildProjectItem.Xml.Location.Line, msBuildProjectItem.Xml.Location.Column);
            Metadata = msBuildProjectItem.Metadata.ToDictionary(m => m.Name, m => m.EvaluatedValue);
            IsLink   = Metadata.ContainsKey("Link");

            if (msBuildProjectItem.UnevaluatedInclude.Contains("*"))
            {
                IsIncludedByWildcard = true;
                WildcardInclude      = msBuildProjectItem.UnevaluatedInclude;
                WildcardExclude      = msBuildProjectItem.Xml.Exclude;
            }

            _identifier = new Lazy <string>(CreateIdentifier);
        }
Exemple #3
0
        /// <param name="eItem"></param>
        public Item(Microsoft.Build.Evaluation.ProjectItem eItem)
            : this()
        {
            if (eItem == null)
            {
                throw new ArgumentNullException(nameof(eItem));
            }

            type = eItem.ItemType;
            unevaluatedInclude = eItem.UnevaluatedInclude;
            evaluatedInclude   = eItem.EvaluatedInclude;
            isImported         = eItem.IsImported;
            parentItem         = eItem;

            meta = eItem.DirectMetadata.Select(m => new KeyValuePair <string, Metadata>
                                               (
                                                   m.Name,
                                                   new Metadata()
            {
                name        = m.Name,
                unevaluated = m.UnevaluatedValue,
                evaluated   = m.EvaluatedValue
            }
                                               )).ToDictionary(m => m.Key, m => m.Value, StringComparer.OrdinalIgnoreCase);
        }
Exemple #4
0
        private static ProjectItemWrapper CreateProjectItemWrapper(ProjectItem item)
        {
            var targetFileName = item.Project.AllEvaluatedProperties.First(property => property.Name == "TargetFileName")
                                 .EvaluatedValue;
            var appendTargetFrameworkToOutputPath = item.Project.AllEvaluatedProperties.FirstOrDefault(property => property.Name == "AppendTargetFrameworkToOutputPath")
                                                    ?.EvaluatedValue;
            var outputPath = GetEvaluatedValue(item, "OutputPath");

            if (appendTargetFrameworkToOutputPath == "true")
            {
                var targetFramework = item.Project.AllEvaluatedProperties.First(property => property.Name == "TargetFramework").EvaluatedValue;
                outputPath += targetFramework;
            }
            var fullPath = GetEvaluatedValue(item, "ProjectDir");

            return(new ProjectItemWrapper {
                Name = GetName(item),
                ModelFileName = Path.GetFileName(item.EvaluatedInclude),
                OutputPath = outputPath,
                OutputFileName = targetFileName,
                IsApplicationProject = Path.GetExtension(targetFileName) == ".exe" || IsWeb(fullPath),
                FullPath = fullPath,
                UniqueName = Path.GetDirectoryName(fullPath) + @"\" + GetEvaluatedValue(item, "ProjectFileName"),
                LocalPath = Path.GetDirectoryName(fullPath) + @"\" + item.EvaluatedInclude
            });
        }
        private static ProjectItemWrapper CreateProjectItemWrapper(ProjectItem item)
        {
            var targetFileName = item.Project.AllEvaluatedProperties.First(property => property.Name == "TargetFileName")
                                 .EvaluatedValue;
            var appendTargetFrameworkToOutputPath = item.Project.AllEvaluatedProperties.FirstOrDefault(property => property.Name == "AppendTargetFrameworkToOutputPath")
                                                    ?.EvaluatedValue;
            var outputPath      = GetEvaluatedValue(item, "OutputPath");
            var targetFramework = item.Project.AllEvaluatedProperties.FirstOrDefault(property => property.Name == "TargetFramework")?.EvaluatedValue;

            if ($"{appendTargetFrameworkToOutputPath}".ToLower() == "true")
            {
                outputPath += targetFramework;
            }
            var fullPath = GetEvaluatedValue(item, "ProjectDir");

            var projectItemWrapper = new ProjectItemWrapper {
                Name                 = GetName(item),
                ModelFileName        = Path.GetFileName(item.EvaluatedInclude),
                OutputPath           = outputPath,
                OutputFileName       = targetFileName,
                FullPath             = fullPath,
                UniqueName           = Path.GetDirectoryName(fullPath) + @"\" + GetEvaluatedValue(item, "ProjectFileName"),
                LocalPath            = Path.GetDirectoryName(fullPath) + @"\" + item.EvaluatedInclude,
                TargetFramework      = targetFramework,
                IsApplicationProject =
                    File.Exists(
                        $"{Path.GetFullPath($"{fullPath}")}\\{outputPath}\\{Path.GetFileNameWithoutExtension(targetFileName)}.exe") || IsWeb(fullPath)
            };

            return(projectItemWrapper);
        }
Exemple #6
0
        public void Remove(object index)
        {
            string?importToRemove = index switch
            {
                int indexInt when _importsList.IsPresent(indexInt) => _importsList.Item(indexInt),
                string removeImport when _importsList.IsPresent(removeImport) => removeImport,
                _ => null
            };

            if (importToRemove != null)
            {
                _threadingService.ExecuteSynchronously(async() =>
                {
                    await _projectAccessor.OpenProjectForWriteAsync(ConfiguredProject, project =>
                    {
                        Microsoft.Build.Evaluation.ProjectItem importProjectItem = project.GetItems(ImportItemTypeName)
                                                                                   .First(i => string.Equals(importToRemove, i.EvaluatedInclude, StringComparisons.ItemNames));

                        if (importProjectItem.IsImported)
                        {
                            throw new ArgumentException(string.Format(VSResources.ImportsFromTargetCannotBeDeleted, importToRemove), nameof(index));
                        }

                        project.RemoveItem(importProjectItem);
                    });

                    await _importsList.ReceiveLatestSnapshotAsync();
                });
            }
            else
            {
                throw new ArgumentException(string.Format("{0} - index is neither an Int nor a String, or the Namepsace was not found", index), nameof(index));
            }
        }
Exemple #7
0
        private void DoAdd(string itemType, string itemPath)
        {
            var added = this.itemProject.BuildProject.AddItem(itemType, Microsoft.Build.BuildEngine.Utilities.Escape(itemPath));

            Debug.Assert(added.Count == 1, "adding a file created more than 1 new item, should not be possible since we escape wildcard characters");
            this.item = added[0];
        }
Exemple #8
0
 protected ProjectNode(ProjectRoot projectRoot, string name, ProjectNode parent,
                       Microsoft.Build.Evaluation.ProjectItem projectItem)
 {
     _projectRoot = projectRoot ?? (this as ProjectRoot);
     Name         = name;
     Parent       = parent;
     ProjectItem  = projectItem;
 }
Exemple #9
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.SetProjectFileDirty(true);
     }
     itemProject = null;
     item        = null;
 }
Exemple #10
0
        public void Remove(object index)
        {
            bool intIndexPresent    = index is int indexInt && _importsList.IsPresent(indexInt);
            bool stringIndexPresent = index is string removeImport && _importsList.IsPresent((string)removeImport);

            if (intIndexPresent || stringIndexPresent)
            {
                string importRemoved = null;
                _threadingService.ExecuteSynchronously(async() =>
                {
                    using (var access = await _lockService.WriteLockAsync())
                    {
                        Microsoft.Build.Evaluation.ProjectItem importProjectItem = null;
                        var project = await access.GetProjectAsync(ConfiguredProject).ConfigureAwait(true);
                        await access.CheckoutAsync(project.Xml.ContainingProject.FullPath).ConfigureAwait(true);
                        if (index is string removeImport1)
                        {
                            importProjectItem = project.GetItems(importItemTypeName)
                                                .First(i => string.Compare(removeImport1, i.EvaluatedInclude, StringComparison.OrdinalIgnoreCase) == 0);
                        }
                        else if (index is int indexInt1)
                        {
                            importProjectItem = project.GetItems(importItemTypeName)
                                                .OrderBy(i => i.EvaluatedInclude)
                                                .ElementAt((indexInt1 - 1));
                        }
                        else
                        {
                            // Cannot reach this point, since index has to be Int or String
                            System.Diagnostics.Debug.Assert(false, $"Parameter {nameof(index)} is niether an int nor a string");
                        }

                        if (importProjectItem.IsImported)
                        {
                            throw new ArgumentException(string.Format(VisualBasicVSResources.ImportsFromTargetCannotBeDeleted, index.ToString()), nameof(index));
                        }

                        importRemoved = importProjectItem.EvaluatedInclude;
                        project.RemoveItem(importProjectItem);
                    }
                });

                OnImportRemoved(importRemoved);
            }
            else if (index is string)
            {
                throw new ArgumentException(string.Format("{0} - Namespace is not present ", index), nameof(index));
            }
            else
            {
                throw new ArgumentException(string.Format("{0} - index is neither an Int nor a String", index), nameof(index));
            }
        }
Exemple #11
0
        public string GetReferenceHint(string refs)
        {
            Microsoft.Build.Evaluation.ProjectItem p = GetReference("Reference", refs);

            if (p == null)
            {
                return("");
            }

            string hint = GetReferenceHint(p);

            return(hint);
        }
Exemple #12
0
 protected Microsoft.Build.Evaluation.ProjectItem GetExistingItem(string absFileName)
 {
     Microsoft.Build.Evaluation.ProjectItem prjItem = null;
     foreach (var item in BuildProject.Items)
     {
         if (item.UnevaluatedInclude == absFileName)
         {
             prjItem = item;
             break;
         }
     }
     return(prjItem);
 }
        // This functions adds node with data that comes from parsing the .rsproj file
        protected override HierarchyNode AddIndependentFileNode(Microsoft.Build.Evaluation.ProjectItem item, HierarchyNode parent)
        {
            var node = (TrackedFileNode)base.AddIndependentFileNode(item, parent);

            if (node.GetModuleTracking())
            {
                if (node.Url.Equals(ModuleTracker.EntryPoint, StringComparison.InvariantCultureIgnoreCase))
                {
                    node.IsEntryPoint  = true;
                    containsEntryPoint = true;
                }
            }
            return(node);
        }
Exemple #14
0
        public virtual void AddReference(string referencePath, Stream stream)
        {
            string name = Path.GetFileNameWithoutExtension(referencePath);

            try {
                // Get the full path to the reference
                string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);

                // Add a reference to the project
                Reference reference = Project.Object.References.Add(fullPath);

                // Always set copy local to true for references that we add
                reference.CopyLocal = true;

                // This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
                // Most commmonly, it happens if this assembly is in the GAC or in the output path.
                if (!reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
                {
                    // Get the msbuild project for this project
                    MsBuildProject buildProject = Project.AsMSBuildProject();

                    if (buildProject != null)
                    {
                        // Get the assembly name of the reference we are trying to add
                        AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);

                        // Try to find the item for the assembly name
                        MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
                                                   where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
                                                   select assemblyReferenceNode.Item1).FirstOrDefault();

                        if (item != null)
                        {
                            // Add the <HintPath> metadata item as a relative path
                            item.SetMetadataValue("HintPath", referencePath);

                            // Save the project after we've modified it.
                            Project.Save();
                        }
                    }
                }

                Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
            }
            catch (Exception e) {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
            }
        }
Exemple #15
0
        string GetAssemblyFileNameFromHintPath(Microsoft.Build.Evaluation.Project p, Microsoft.Build.Evaluation.ProjectItem item)
        {
            string assemblyFileName = null;

            if (item.HasMetadata("HintPath"))
            {
                assemblyFileName = _fileSystem.Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath")).ForceNativePathSeparator();
                _logger.Info("Looking for assembly from HintPath at " + assemblyFileName);
                if (!_fileSystem.File.Exists(assemblyFileName))
                {
                    _logger.Info("Did not find assembly from HintPath");
                    assemblyFileName = null;
                }
            }
            return(assemblyFileName);
        }
Exemple #16
0
        private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
        {
            var references = _loadedProject.GetItems(ItemNames.Reference);

            MSB.Evaluation.ProjectItem item = null;

            var fileName = Path.GetFileNameWithoutExtension(filePath);

            if (identity != null)
            {
                var shortAssemblyName = identity.Name;
                var fullAssemblyName  = identity.GetDisplayName();

                // check for short name match
                item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);

                // check for full name match
                if (item == null)
                {
                    item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
                }
            }

            // check for file path match
            if (item == null)
            {
                var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);

                item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath) ||
                                                 PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                                 PathUtilities.PathsEqual(GetHintPath(it), filePath) ||
                                                 PathUtilities.PathsEqual(GetHintPath(it), relativePath));
            }

            // check for partial name match
            if (item == null && identity != null)
            {
                var partialName = identity.Name + ",";
                var items       = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
                if (items.Count == 1)
                {
                    item = items[0];
                }
            }

            return(item);
        }
Exemple #17
0
        static public IEnumerable <ProjectItemWrapper> GetChildItemsFromFolder(FolderWalker folderWalker)
        {
            // Return the files:
            // IMPORTANT: we sort the files by name so that the files ".XAML" are returned before their code-behind ".XAML.CS". This order is important because when we copy the former, the latter gets copied as well. So when we arrive to the code-behind, we skip it because we are able to check that it already exists. If, on the contrary, we did the other way around, we would get an error when copying the ".XAML" because it says that it cannot copy the ".XAML.CS" because it already exists.
            foreach (FileWalker fileWalker in folderWalker.GetFiles(sortByName: true))
            {
                Microsoft.Build.Evaluation.ProjectItem projectItem = (Microsoft.Build.Evaluation.ProjectItem)fileWalker.UserState;

                yield return(new ProjectItemWrapper(projectItem, fileWalker));
            }

            // And also return then the sub-folders:
            foreach (FolderWalker subFolderWalker in folderWalker.GetFolders())
            {
                yield return(new ProjectItemWrapper(subFolderWalker));
            }
        }
Exemple #18
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;
            }

            itemProject.BuildProject.ReevaluateIfNecessary();

            foreach (var projectItem in itemProject.BuildProject.GetItems(item.ItemType))
            {
                if (projectItem != null && projectItem.UnevaluatedInclude.Equals(item.UnevaluatedInclude))
                {
                    item = projectItem;
                    return;
                }
            }
        }
Exemple #19
0
        public string GetReferenceHint(Microsoft.Build.Evaluation.ProjectItem p)
        {
            if (p.HasMetadata("HintPath") == false)
            {
                return("");
            }


            foreach (Microsoft.Build.Evaluation.ProjectMetadata m in p.Metadata)
            {
                if (m.Name == "HintPath")
                {
                    return(m.UnevaluatedValue);
                }
            }


            return("");
        }
        public ProjectReference(ISolution solution, Microsoft.Build.Evaluation.ProjectItem projectItem)
        {
            OriginalProjectItem = projectItem;
            Include             = projectItem.EvaluatedInclude;

            var fullPath = Path.GetFullPath(Path.Combine(projectItem.Project.DirectoryPath, Include));

            File    = Wrapper.Wrap(new FileInfo(fullPath));
            Project = solution.GetProjectByAbsoluteProjectFilePath(fullPath);

            Guid referencedProjectGuid;

            if (Guid.TryParse(projectItem.GetMetadataValue("Project"), out referencedProjectGuid))
            {
                ReferencedProjectGuid = referencedProjectGuid;
            }

            ReferencedProjectName = projectItem.GetMetadataValue("Name");
        }
Exemple #21
0
        private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
        {
            var references   = _loadedProject.GetItems(ItemNames.ProjectReference);
            var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);

            MSB.Evaluation.ProjectItem item = null;

            // find by project file path
            item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                    PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));

            // try to find by project name
            if (item == null)
            {
                item = references.First(it => string.Compare(projectName, it.GetMetadataValue(MetadataNames.Name), StringComparison.OrdinalIgnoreCase) == 0);
            }

            return(item);
        }
Exemple #22
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Microsoft.Build.Evaluation.Project buildProject = buildProjectInfo.GetValue(testEnv.Project, new object[0]) as Microsoft.Build.Evaluation.Project;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                MethodInfo itemMapGetter           = typeof(VisualStudio.Project.ProjectNode).GetProperty("ItemIdMap", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true);
                Microsoft.VisualStudio.Shell.EventSinkCollection itemMap = (Microsoft.VisualStudio.Shell.EventSinkCollection)itemMapGetter.Invoke(testEnv.Project, new object[0]);
                uint itemID = itemMap.Add(node);

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Exemple #23
0
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have public 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>
        public ProjectElement(ProjectNode project, Microsoft.Build.Evaluation.ProjectItem 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>();
            }
        }
Exemple #24
0
        private void CommandQueryStatus(object sender, EventArgs e)
        {
            OleMenuCommand oCommand = ( OleMenuCommand )sender;

            Microsoft.Build.Evaluation.ProjectItem     oItem     = GetProjectItem(ProjectItem.Name);
            Microsoft.Build.Evaluation.ProjectMetadata oMetadata = oItem.Metadata.SingleOrDefault(oProperty => oProperty.Name == "Generator");
            bool bFit = false;

            if (oMetadata != null)
            {
                string szTool = oMetadata.EvaluatedValue;

                if (szTool.ToUpper( ) == Consts.Me.ToUpper( ))
                {
                    bFit = true;
                }
            }

            if (!bFit)
            {
                oMetadata = oItem.Metadata.SingleOrDefault(oProperty => oProperty.Name == "DependentUpon");

                if (oMetadata != null)
                {
                    oItem = GetProjectItem(oMetadata.EvaluatedValue);

                    oMetadata = oItem.Metadata.SingleOrDefault(oProperty => oProperty.Name == "Generator");

                    string szTool = oMetadata.EvaluatedValue;

                    if (szTool.ToUpper( ) == Consts.Me.ToUpper( ))
                    {
                        bFit = true;
                    }
                }
            }

            oCommand.Visible = bFit;
        }
Exemple #25
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                Microsoft.Build.Evaluation.Project buildProject = testEnv.Project.BuildProject;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                uint itemID = node.Id;

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Exemple #26
0
        private void CommandInvoke(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs oOleMenuCmdEventArgs = ( OleMenuCmdEventArgs )e;

            Microsoft.Build.Evaluation.ProjectItem oItem = GetProjectItem(ProjectItem.Name);

            if (oOleMenuCmdEventArgs.OutValue != IntPtr.Zero)
            {
                string szOut = string.IsNullOrEmpty(oItem.Xml.Condition) ? "Default" : oItem.Xml.Condition.Replace("'$(Configuration)' ==", string.Empty).Replace("'", string.Empty).Trim( );

                Marshal.GetNativeVariantForObject(szOut, oOleMenuCmdEventArgs.OutValue);
            }
            else if (oOleMenuCmdEventArgs.InValue != null)
            {
                switch (Convert.ToString(oOleMenuCmdEventArgs.InValue))
                {
                case "Default":
                {
                    oItem.Xml.Condition = string.Empty;
                }
                break;

                case "Debug":
                {
                    oItem.Xml.Condition = " '$(Configuration)' == 'Debug' ";
                }
                break;

                case "Release":
                {
                    oItem.Xml.Condition = " '$(Configuration)' == 'Release' ";
                }
                break;
                }
            }
        }
Exemple #27
0
        public virtual void AddReference(string referencePath, Stream stream)
        {
            string name = Path.GetFileNameWithoutExtension(referencePath);

            try
            {
                // Get the full path to the reference
                string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);

                string assemblyPath = fullPath;
                bool   usedTempFile = false;

                // There is a bug in Visual Studio whereby if the fullPath contains a comma,
                // then calling Project.Object.References.Add() on it will throw a COM exception.
                // To work around it, we copy the assembly into temp folder and add reference to the copied assembly
                if (fullPath.Contains(","))
                {
                    string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath));
                    File.Copy(fullPath, tempFile, true);
                    assemblyPath = tempFile;
                    usedTempFile = true;
                }

                // Add a reference to the project
                Reference reference = Project.Object.References.Add(assemblyPath);

                // if we copied the assembly to temp folder earlier, delete it now since we no longer need it.
                if (usedTempFile)
                {
                    try
                    {
                        File.Delete(assemblyPath);
                    }
                    catch
                    {
                        // don't care if we fail to delete a temp file
                    }
                }

                TrySetCopyLocal(reference);

                // This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
                // Most commonly, it happens if this assembly is in the GAC or in the output path.
                if (!reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
                {
                    // Get the msbuild project for this project
                    MsBuildProject buildProject = Project.AsMSBuildProject();

                    if (buildProject != null)
                    {
                        // Get the assembly name of the reference we are trying to add
                        AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);

                        // Try to find the item for the assembly name
                        MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
                                                   where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
                                                   select assemblyReferenceNode.Item1).FirstOrDefault();

                        if (item != null)
                        {
                            // Add the <HintPath> metadata item as a relative path
                            item.SetMetadataValue("HintPath", referencePath);

                            // Save the project after we've modified it.
                            Project.Save();
                        }
                    }
                }

                Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
            }
        }
        private void DoAdd(string itemType, string itemPath)
        {
            var added = this.itemProject.BuildProject.AddItem(itemType, Microsoft.Build.BuildEngine.Utilities.Escape(itemPath));
            Debug.Assert(added.Count == 1, "adding a file created more than 1 new item, should not be possible since we escape wildcard characters");
            this.item = added[0];

        }
Exemple #29
0
 private static string GetHintPath(MSB.Evaluation.ProjectItem item)
 => item.Metadata.FirstOrDefault(m => string.Equals(m.Name, MetadataNames.HintPath, StringComparison.OrdinalIgnoreCase))?.EvaluatedValue ?? string.Empty;
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.BuildItem
        /// Only have public 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>
        public ProjectElement(ProjectNode project, Microsoft.Build.Evaluation.ProjectItem 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>();
        }
 public static ProjectItem FromMsBuildProjectItem(IProject project, Microsoft.Build.Evaluation.ProjectItem msBuildProjectItem)
 {
     return(new ProjectItem(project, msBuildProjectItem));
 }
 /// <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.SetProjectFileDirty(true);
     }
     itemProject = null;
     item = null;
 }
        /// <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;

            itemProject.BuildProject.ReevaluateIfNecessary();

            foreach (var projectItem in itemProject.BuildProject.GetItems(item.ItemType))
            {
                if(projectItem!= null && projectItem.UnevaluatedInclude.Equals(item.UnevaluatedInclude))
                {
                    item = projectItem;
                    return;
                }
            }
        }
Exemple #34
0
 internal void AddChild(string name, Microsoft.Build.Evaluation.ProjectItem projectItem) =>
 _children.Add(name, new ProjectNode(_projectRoot, name, this, projectItem));