Ejemplo n.º 1
0
 /// <summary>
 /// Initialize an unparented ProjectItemElement instance
 /// </summary>
 private ProjectItemElement(XmlElementWithLocation xmlElement, ProjectRootElement containingProject)
     : base(xmlElement, null, containingProject)
 {
 }
Ejemplo n.º 2
0
 public abstract ProjectElement CreateNewInstance(ProjectRootElement owner);
        public void FindItems()
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create(@"src\project.csproj");

            // AllowedReferenceRelatedFileExtensions is usually set in Microsoft.Common.CurrentVersion.targets
            const string allowedReferenceRelatedFileExtensions = @"
      .pdb;
      .xml;
      .pri;
      .dll.config;
      .exe.config
";

            projectRootElement.AddProperty(ReferenceItemsPredictor.AllowedReferenceRelatedFileExtensionsPropertyName, allowedReferenceRelatedFileExtensions);

            // Reference using HintPath - Is an input
            projectRootElement
            .AddItem(ReferenceItemsPredictor.ReferenceItemName, "Reference1")
            .AddMetadata(ReferenceItemsPredictor.HintPathMetadata, @"..\packages\Package1\lib\net45\Reference1.dll");

            // Reference not using HintPath (usually uses <Name> though) - Is an input
            projectRootElement
            .AddItem(ReferenceItemsPredictor.ReferenceItemName, @"..\packages\Package2\lib\net45\Reference2.dll")
            .AddMetadata("Name", "Reference2");

            // Reference adjacent to the project (must exist) - Is an input
            projectRootElement.AddItem(ReferenceItemsPredictor.ReferenceItemName, @"CheckedInAssembly.dll");
            Directory.CreateDirectory("src");
            File.WriteAllText(@"src\CheckedInAssembly.dll", "SomeContent");

            // Reference with related files (which must exist) - Is an input as well as related files
            projectRootElement
            .AddItem(ReferenceItemsPredictor.ReferenceItemName, @"..\packages\Package3\lib\net45\Reference3.dll")
            .AddMetadata("Name", "Reference3");
            Directory.CreateDirectory(@"packages\Package3\lib\net45");
            File.WriteAllText(@"packages\Package3\lib\net45\Reference3.dll", "SomeContent");
            File.WriteAllText(@"packages\Package3\lib\net45\Reference3.pdb", "SomeContent");
            File.WriteAllText(@"packages\Package3\lib\net45\Reference3.xml", "SomeContent");

            // References from the platform or GAC - NOT inputs
            projectRootElement.AddItem(ReferenceItemsPredictor.ReferenceItemName, "System.Data");
            projectRootElement.AddItem(ReferenceItemsPredictor.ReferenceItemName, "System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

            ProjectInstance projectInstance = TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement);

            var expectedInputFiles = new[]
            {
                new PredictedItem(@"packages\Package1\lib\net45\Reference1.dll", nameof(ReferenceItemsPredictor)),
                new PredictedItem(@"packages\Package2\lib\net45\Reference2.dll", nameof(ReferenceItemsPredictor)),
                new PredictedItem(@"packages\Package3\lib\net45\Reference3.dll", nameof(ReferenceItemsPredictor)),
                new PredictedItem(@"packages\Package3\lib\net45\Reference3.pdb", nameof(ReferenceItemsPredictor)),
                new PredictedItem(@"packages\Package3\lib\net45\Reference3.xml", nameof(ReferenceItemsPredictor)),
                new PredictedItem(@"src\CheckedInAssembly.dll", nameof(ReferenceItemsPredictor)),
            };

            new ReferenceItemsPredictor()
            .GetProjectPredictions(projectInstance)
            .AssertPredictions(
                projectInstance,
                expectedInputFiles.MakeAbsolute(Directory.GetCurrentDirectory()),
                null,
                null,
                null);
        }
Ejemplo n.º 4
0
 public Guid GetProjectId(ProjectRootElement project)
 {
     var value = project.Properties.Where (p => p.Name == "ProjectGuid").First ().Value;
                 return Guid.Parse (value);
 }
Ejemplo n.º 5
0
        private IEnumerable <string> GetAllProjectReferenceNames(Project project, NuGetFramework framework, ProjectRootElement xproj)
        {
            var csprojReferenceItems         = _projectDependencyFinder.ResolveXProjProjectDependencies(xproj);
            var migratedXProjDependencyPaths = csprojReferenceItems.SelectMany(p => p.Includes());
            var migratedXProjDependencyNames = new HashSet <string>(migratedXProjDependencyPaths.Select(p => Path.GetFileNameWithoutExtension(
                                                                                                            PathUtility.GetPathWithDirectorySeparator(p))));
            var projectDependencies = _projectDependencyFinder.ResolveProjectDependenciesForFramework(
                project,
                framework,
                preResolvedProjects: migratedXProjDependencyNames);

            return(projectDependencies.Select(p => p.Name).Concat(migratedXProjDependencyNames));
        }
Ejemplo n.º 6
0
        public static IProjectAccessor Create(ProjectRootElement rootElement)
        {
            var evaluationProject = ProjectFactory.Create(rootElement);

            return(new ProjectAccessor(rootElement, evaluationProject));
        }
Ejemplo n.º 7
0
 public static bool HasItem(this ProjectRootElement root, string itemType, string include, bool noCondition = false)
 {
     return(root.FindItemOrNull(itemType, include, noCondition) != null);
 }
Ejemplo n.º 8
0
 internal override void OnProjectRootElementDirtied(ProjectRootElement sender, ProjectXmlChangedEventArgs e)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 9
0
 protected override void RaiseProjectRootElementRemovedFromStrongCache(ProjectRootElement projectRootElement)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 10
0
        protected override ProjectUpgradeState UpgradeProjectCheck(ProjectRootElement projectXml, ProjectRootElement userProjectXml, Action <__VSUL_ERRORLEVEL, string> log, ref Guid projectFactory, ref __VSPPROJECTUPGRADEVIAFACTORYFLAGS backupSupport)
        {
            var envVarsProp = projectXml.Properties.FirstOrDefault(p => p.Name == NodejsConstants.EnvironmentVariables);

            if (envVarsProp != null && !string.IsNullOrEmpty(envVarsProp.Value))
            {
                return(ProjectUpgradeState.OneWayUpgrade);
            }

            return(ProjectUpgradeState.NotNeeded);
        }
Ejemplo n.º 11
0
        internal IEnumerable <ProjectPropertyInstance> GetReservedProperties(Toolset toolset, ProjectInstance project, ProjectRootElement xml)
        {
            Func <string, Func <string>, ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance(name, true, null, value);

            return(GetReservedProperties <ProjectPropertyInstance> (toolset, xml, create, () => project.FullPath));
        }
Ejemplo n.º 12
0
 private IEnumerable <ProjectItemElement> FindExistingItems(ProjectItemElement item, ProjectRootElement project)
 {
     return(project.ItemsWithoutConditions()
            .Where(i => string.Equals(i.ItemType, item.ItemType, StringComparison.Ordinal))
            .Where(i => i.IntersectIncludes(item).Any()));
 }
 public MSBuildProjectRootElement(ProjectRootElement rootElement)
 {
     _rootElement = rootElement;
 }
        /// <summary>
        /// Deletes items from the project, and optionally from disk.
        /// Note: Delete and Remove commands are handled via IVsHierarchyDeleteHandler3, not by
        /// IAsyncCommandGroupHandler and first asks us we CanRemove nodes. If yes then RemoveAsync is called.
        /// We can remove only nodes that are standard and based on project items, i.e. nodes that
        /// are created by default IProjectDependenciesSubTreeProvider implementations and have
        /// DependencyNode.GenericDependencyFlags flags and IRule with Context != null, in order to obtain
        /// node's itemSpec. ItemSpec then used to remove a project item having same Include.
        /// </summary>
        /// <param name="nodes">The nodes that should be deleted.</param>
        /// <param name="deleteOptions">A value indicating whether the items should be deleted from disk as well as
        /// from the project file.
        /// </param>
        /// <exception cref="InvalidOperationException">Thrown when <see cref="IProjectTreeProvider.CanRemove"/>
        /// would return <c>false</c> for this operation.</exception>
        public override async Task RemoveAsync(IImmutableSet <IProjectTree> nodes,
                                               DeleteOptions deleteOptions = DeleteOptions.None)
        {
            if (deleteOptions.HasFlag(DeleteOptions.DeleteFromStorage))
            {
                throw new NotSupportedException();
            }

            // Get the list of shared import nodes.
            IEnumerable <IProjectTree> sharedImportNodes = nodes.Where(node =>
                                                                       node.Flags.Contains(DependencyTreeFlags.SharedProjectFlags));

            // Get the list of normal reference Item Nodes (this excludes any shared import nodes).
            IEnumerable <IProjectTree> referenceItemNodes = nodes.Except(sharedImportNodes);

            await _projectAccessor.OpenProjectForWriteAsync(ActiveConfiguredProject, project =>
            {
                // Handle the removal of normal reference Item Nodes (this excludes any shared import nodes).
                foreach (IProjectTree node in referenceItemNodes)
                {
                    if (node.BrowseObjectProperties?.Context == null)
                    {
                        // if node does not have an IRule with valid ProjectPropertiesContext we can not
                        // get its itemsSpec. If nodes provided by custom IProjectDependenciesSubTreeProvider
                        // implementation, and have some custom IRule without context, it is not a problem,
                        // since they would not have DependencyNode.GenericDependencyFlags and we would not
                        // end up here, since CanRemove would return false and Remove command would not show
                        // up for those nodes.
                        continue;
                    }

                    IProjectPropertiesContext nodeItemContext = node.BrowseObjectProperties.Context;
                    ProjectItem?unresolvedReferenceItem       = project.GetItemsByEvaluatedInclude(nodeItemContext.ItemName)
                                                                .FirstOrDefault(
                        (item, t) => string.Equals(item.ItemType, t, StringComparisons.ItemTypes),
                        nodeItemContext.ItemType);

                    Report.IfNot(unresolvedReferenceItem != null, "Cannot find reference to remove.");
                    if (unresolvedReferenceItem != null)
                    {
                        project.RemoveItem(unresolvedReferenceItem);
                    }
                }

                DependenciesSnapshot snapshot = _dependenciesSnapshotProvider.CurrentSnapshot;
                Requires.NotNull(snapshot, nameof(snapshot));
                if (snapshot == null)
                {
                    return;
                }

                // Handle the removal of shared import nodes.
                ProjectRootElement projectXml = project.Xml;
                foreach (IProjectTree sharedImportNode in sharedImportNodes)
                {
                    string sharedFilePath = UnconfiguredProject.MakeRelative(sharedImportNode.FilePath);
                    if (string.IsNullOrEmpty(sharedFilePath))
                    {
                        continue;
                    }

                    IDependency?sharedProjectDependency = snapshot.FindDependency(sharedFilePath, topLevel: true);
                    if (sharedProjectDependency != null)
                    {
                        sharedFilePath = sharedProjectDependency.Path;
                    }

                    // Find the import that is included in the evaluation of the specified ConfiguredProject that
                    // imports the project file whose full path matches the specified one.
                    IEnumerable <ResolvedImport> matchingImports = from import in project.Imports
                                                                   where import.ImportingElement.ContainingProject == projectXml &&
                                                                   PathHelper.IsSamePath(import.ImportedProject.FullPath, sharedFilePath)
                                                                   select import;
                    foreach (ResolvedImport importToRemove in matchingImports)
                    {
                        ProjectImportElement importingElementToRemove = importToRemove.ImportingElement;
                        Report.IfNot(importingElementToRemove != null,
                                     "Cannot find shared project reference to remove.");
                        if (importingElementToRemove != null)
                        {
                            importingElementToRemove.Parent.RemoveChild(importingElementToRemove);
                        }
                    }
                }
            });
        }
Ejemplo n.º 15
0
 public ProjectRootElement CsProj()
 {
     // Passing new collection to prevent using cached version
     return(ProjectRootElement.Open(CsProjPath, new ProjectCollection()));
 }
Ejemplo n.º 16
0
 internal override void RenameEntry(string oldFullPath, ProjectRootElement projectRootElement)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Gets xml data as ProjectRootElement from string.
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 protected ProjectRootElement getXml(string data)
 {
     using (StringReader reader = new StringReader(data)) {
         return(ProjectRootElement.Create(System.Xml.XmlReader.Create(reader)));
     }
 }
Ejemplo n.º 18
0
 public Project(XmlReader xml)
     : this(ProjectRootElement.Create(xml))
 {
 }
Ejemplo n.º 19
0
 public ProjectAccessor(ProjectRootElement element, Project project)
 {
     _rootElement       = element;
     _evaluationProject = project;
 }
Ejemplo n.º 20
0
 public Project(XmlReader xml, IDictionary <string, string> globalProperties,
                string toolsVersion)
     : this(ProjectRootElement.Create(xml), globalProperties, toolsVersion)
 {
 }
Ejemplo n.º 21
0
        public void ReadNone()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            Assert.Null(project.Imports.GetEnumerator().Current);
        }
Ejemplo n.º 22
0
 public Project(XmlReader xml, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection,
                ProjectLoadSettings loadSettings)
     : this(ProjectRootElement.Create(xml), globalProperties, toolsVersion, projectCollection, loadSettings)
 {
 }
Ejemplo n.º 23
0
 public static Project Create(ProjectRootElement rootElement)
 {
     return(new Project(rootElement));
 }
Ejemplo n.º 24
0
 public Project(ProjectRootElement xml) : this(xml, null, null)
 {
 }
Ejemplo n.º 25
0
        internal static void WriteProjectXml(
            IInterpreterRegistryService service,
            TextWriter writer,
            string projectPath,
            string sourcePath,
            string filters,
            string searchPaths,
            string startupFile,
            PythonInterpreterView selectedInterpreter,
            ProjectCustomization customization,
            bool detectVirtualEnv
            )
        {
            var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath);

            var project = ProjectRootElement.Create();

            project.DefaultTargets = "Build";
            project.ToolsVersion   = "4.0";

            var globals = project.AddPropertyGroup();

            globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
            globals.AddProperty("SchemaVersion", "2.0");
            globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B"));
            globals.AddProperty("ProjectHome", projectHome);
            if (PathUtils.IsValidPath(startupFile))
            {
                globals.AddProperty("StartupFile", startupFile);
            }
            else
            {
                globals.AddProperty("StartupFile", "");
            }
            globals.AddProperty("SearchPath", searchPaths);
            globals.AddProperty("WorkingDirectory", ".");
            globals.AddProperty("OutputPath", ".");

            globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}");
            globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName);

            var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, "");

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id))
            {
                interpreterId.Value = selectedInterpreter.Id;
            }

            // VS requires property groups with conditions for Debug
            // and Release configurations or many COMExceptions are
            // thrown.
            var debugGroup   = project.AddPropertyGroup();
            var releaseGroup = project.AddPropertyGroup();

            debugGroup.Condition   = "'$(Configuration)' == 'Debug'";
            releaseGroup.Condition = "'$(Configuration)' == 'Release'";


            var folders         = new HashSet <string>();
            var virtualEnvPaths = detectVirtualEnv ? new List <string>() : null;

            foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths))
            {
                var file     = ProjectCollection.Escape(unescapedFile);
                var ext      = Path.GetExtension(file);
                var fileType = "Content";
                if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) ||
                    PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase))
                {
                    fileType = "Compile";
                }
                folders.Add(Path.GetDirectoryName(file));

                project.AddItem(fileType, file);
            }

            foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s))
            {
                project.AddItem("Folder", folder);
            }

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id))
            {
                project.AddItem(
                    MSBuildConstants.InterpreterReferenceItem,
                    selectedInterpreter.Id
                    );
            }
            if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null)
            {
                foreach (var path in virtualEnvPaths)
                {
                    var shortId = PathUtils.GetFileOrDirectoryName(path);
                    var longId  = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", shortId);
                    var config  = VirtualEnv.FindInterpreterConfiguration(longId, path, service);
                    if (config != null)
                    {
                        AddVirtualEnvironment(project, sourcePath, shortId, config);

                        if (string.IsNullOrEmpty(interpreterId.Value))
                        {
                            interpreterId.Value = longId;
                        }
                    }
                }
            }

            var imports = project.AddPropertyGroup();

            imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' ";

            (customization ?? DefaultProjectCustomization.Instance).Process(
                sourcePath,
                project,
                new Dictionary <string, ProjectPropertyGroupElement> {
                { "Globals", globals },
                { "Imports", imports },
                { "Debug", debugGroup },
                { "Release", releaseGroup }
            }
                );

            project.Save(writer);
        }
Ejemplo n.º 26
0
 public Project(ProjectRootElement xml, IDictionary <string, string> globalProperties,
                string toolsVersion)
     : this(xml, globalProperties, toolsVersion, ProjectCollection.GlobalProjectCollection)
 {
 }
Ejemplo n.º 27
0
 public static ProjectElement CreateNewInstance(ProjectElement xml, ProjectRootElement owner) => ProjectElement.CreateNewInstance(xml, owner);
Ejemplo n.º 28
0
 public Project(ProjectRootElement xml, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection)
     : this(xml, globalProperties, toolsVersion, projectCollection, ProjectLoadSettings.Default)
 {
 }
Ejemplo n.º 29
0
        private static AvoidPersistingProjectGuidStorageProvider CreateInstance(ProjectRootElement projectXml)
        {
            var projectAccessor = IProjectAccessorFactory.Create(projectXml);

            return(new AvoidPersistingProjectGuidStorageProvider(projectAccessor, UnconfiguredProjectFactory.Create()));
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Initialize a parented ProjectItemElement instance
 /// </summary>
 internal ProjectItemElement(XmlElementWithLocation xmlElement, ProjectItemGroupElement parent, ProjectRootElement containingProject)
     : base(xmlElement, parent, containingProject)
 {
     ErrorUtilities.VerifyThrowArgumentNull(parent, nameof(parent));
 }