Esempio n. 1
0
        public static void AddTargetsFileToOldProjects(VCProject vcProject)
        {
            string             projectFilePath         = vcProject.ProjectFile;
            ProjectRootElement projectRootElement      = ProjectRootElement.Open(projectFilePath);
            ICollection <ProjectImportElement> imports = projectRootElement.Imports;
            ProjectPropertyGroupElement        userMacrosPropertyGroup = projectRootElement.PropertyGroups.Where(g => g.Label.Equals("UserMacros")).FirstOrDefault();
            ProjectImportElement userFileImport = imports.Where(i => i.Project.Equals("$(VCTargetsPath)\\Microsoft.Cpp.targets")).FirstOrDefault();

            if (userMacrosPropertyGroup != null && !userMacrosPropertyGroup.NextSibling.Equals(userFileImport))
            {
                projectRootElement.RemoveChild(userFileImport);

                projectRootElement.InsertAfterChild(userFileImport, userMacrosPropertyGroup);

                //delete all occurences of PLCnCLIIncludes and PLCnCLIMacros -> saved in .users file now
                IEnumerable <ProjectPropertyElement> elementsToDelete = projectRootElement.PropertyGroups
                                                                        .Where(g => g.Label.Equals("Configuration"))
                                                                        .SelectMany(g => g.Properties
                                                                                    .Where(p => p.Name.Equals("PLCnCLIMacros") || p.Name.Equals("PLCnCLIIncludes")));
                elementsToDelete.ToList().ForEach(e => e.Parent.RemoveChild(e));

                MessageBox.Show("The project file needs to be updated outside of the environment. Please choose 'Reload all...' in the next dialog.",
                                "Project update needed", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                projectRootElement.Save();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Replaces all configuration propertygroups with empty property groups corresponding to the expected configurations.
        /// Doesn't attempt to preserve any content since it can all be regenerated.
        /// Does attempt to preserve the ordering in the project file.
        /// </summary>
        /// <param name="project">Project</param>
        /// <param name="oldPropertyGroups">PropertyGroups to remove</param>
        /// <param name="newConfigurations"></param>
        private static void ReplaceConfigurationPropertyGroups(ProjectRootElement project, IEnumerable <ProjectPropertyGroupElement> oldPropertyGroups, IEnumerable <string> newConfigurations)
        {
            ProjectElement insertAfter = null, insertBefore = null;

            foreach (var oldPropertyGroup in oldPropertyGroups)
            {
                insertBefore = oldPropertyGroup.NextSibling;
                project.RemoveChild(oldPropertyGroup);
            }

            if (insertBefore == null)
            {
                // find first itemgroup after imports
                var insertAt = project.Imports.FirstOrDefault()?.NextSibling;

                while (insertAt != null)
                {
                    if (insertAt is ProjectItemGroupElement)
                    {
                        insertBefore = insertAt;
                        break;
                    }

                    insertAt = insertAt.NextSibling;
                }
            }

            if (insertBefore == null)
            {
                // find last propertygroup after imports, defaulting to after imports
                insertAfter = project.Imports.FirstOrDefault();

                while (insertAfter?.NextSibling != null && insertAfter.NextSibling is ProjectPropertyGroupElement)
                {
                    insertAfter = insertAfter.NextSibling;
                }
            }


            foreach (var newConfiguration in newConfigurations)
            {
                var newPropertyGroup = project.CreatePropertyGroupElement();
                newPropertyGroup.Condition = $"'$(Configuration)|$(Platform)' == '{newConfiguration}'";
                if (insertBefore != null)
                {
                    project.InsertBeforeChild(newPropertyGroup, insertBefore);
                }
                else if (insertAfter != null)
                {
                    project.InsertAfterChild(newPropertyGroup, insertAfter);
                }
                else
                {
                    project.AppendChild(newPropertyGroup);
                }
                insertBefore = null;
                insertAfter  = newPropertyGroup;
            }
        }
Esempio n. 3
0
        private static void InitializeExtensibilityDebugParameters(ProjectRootElement root)
        {
            ProjectElement firstChild         = root.FirstChild;
            ProjectPropertyGroupElement group = root.CreatePropertyGroupElement();

            root.InsertAfterChild(group, firstChild);
            group.AddProperty("StartAction", "Program");
            group.AddProperty("StartProgram", "$(DevEnvDir)\\devenv.exe");
            group.AddProperty("StartArguments", "/RootSuffix Exp");
        }
Esempio n. 4
0
        private bool EnsureProjectGuid(ProjectRootElement project)
        {
            ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
            string guid = string.Empty;

            if (projectGuid != null)
            {
                guid = projectGuid.Value;
                string projectName;
                if (_guidMap.TryGetValue(guid, out projectName))
                {
                    Log.LogMessage($"The ProjectGuid='{guid}' is duplicated across projects '{projectName}' and '{project.FullPath}', so creating a new one for project '{project.FullPath}'");
                    guid = Guid.NewGuid().ToString("B").ToUpper();
                    _guidMap.Add(guid, project.FullPath);
                    projectGuid.Value = guid;
                    return(true);
                }
                else
                {
                    _guidMap.Add(guid, project.FullPath);
                }
            }

            if (projectGuid == null)
            {
                guid = Guid.NewGuid().ToString("B").ToUpper();

                var propertyGroup = project.Imports.FirstOrDefault()?.NextSibling as ProjectPropertyGroupElement;

                if (propertyGroup == null || !string.IsNullOrEmpty(propertyGroup.Condition))
                {
                    propertyGroup = project.CreatePropertyGroupElement();
                    ProjectElement insertAfter = project.Imports.FirstOrDefault();

                    if (insertAfter == null)
                    {
                        insertAfter = project.Children.FirstOrDefault();
                    }

                    if (insertAfter != null)
                    {
                        project.InsertAfterChild(propertyGroup, insertAfter);
                    }
                    else
                    {
                        project.AppendChild(propertyGroup);
                    }
                }

                propertyGroup.AddProperty("ProjectGuid", guid);
                return(true);
            }

            return(false);
        }
Esempio n. 5
0
        private static void InitializeLegacyProjectImports(ProjectRootElement root)
        {
            ProjectElement       firstChild   = root.FirstChild;
            ProjectElement       lastChild    = root.LastChild;
            ProjectImportElement commonImport =
                root.CreateImportElement("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props");

            commonImport.Condition = "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')";
            ProjectImportElement csharpImport =
                root.CreateImportElement("$(MSBuildToolsPath)\\Microsoft.CSharp.targets");

            root.InsertBeforeChild(commonImport, firstChild);
            root.InsertAfterChild(csharpImport, lastChild);
        }
Esempio n. 6
0
        private void InitializeCPSProjectXml()
        {
            _project = new Project(NewProjectFileOptions.None);
            ProjectRootElement   root                  = _project.Xml;
            ProjectElement       firstChild            = root.FirstChild;
            ProjectElement       lastChild             = root.LastChild;
            ProjectImportElement sdkPropsImportElement = root.CreateImportElement("Sdk.props");

            sdkPropsImportElement.Sdk = "Microsoft.NET.Sdk";
            ProjectImportElement sdkTargetsImportElement = root.CreateImportElement("Sdk.targets");

            sdkTargetsImportElement.Sdk = "Microsoft.NET.Sdk";
            root.InsertBeforeChild(sdkPropsImportElement, firstChild);
            root.InsertAfterChild(sdkTargetsImportElement, lastChild);
        }
Esempio n. 7
0
        private static void InitializeCPSProjectImports(ProjectRootElement root)
        {
            ProjectElement       firstChild = root.FirstChild;
            ProjectElement       lastChild  = root.LastChild;
            ProjectImportElement sdkProps   =
                root.CreateImportElement("Sdk.props");

            sdkProps.Sdk = "Microsoft.NET.Sdk";
            ProjectImportElement sdkTargets =
                root.CreateImportElement("Sdk.targets");

            sdkTargets.Sdk = "Microsoft.NET.Sdk";
            root.InsertBeforeChild(sdkProps, firstChild);
            root.InsertAfterChild(sdkTargets, lastChild);
        }
Esempio n. 8
0
        private void InitializeLegacyProjectXml()
        {
            _projectCollection = new ProjectCollection();
            _project           = new Project(new Dictionary <string, string>(), "12.0", _projectCollection, NewProjectFileOptions.IncludeXmlNamespace | NewProjectFileOptions.IncludeToolsVersion);
            ProjectRootElement   root         = _project.Xml;
            ProjectElement       firstChild   = root.FirstChild;
            ProjectElement       lastChild    = root.LastChild;
            ProjectImportElement commonImport =
                root.CreateImportElement("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props");

            commonImport.Condition = "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')";
            ProjectImportElement csharpImport =
                root.CreateImportElement("$(MSBuildToolsPath)\\Microsoft.CSharp.targets");

            root.InsertBeforeChild(commonImport, firstChild);
            root.InsertAfterChild(csharpImport, lastChild);
        }
        public static ProjectItemGroupElement FindUniformOrCreateItemGroupWithCondition(this ProjectRootElement root, string projectItemElementType, string framework)
        {
            var lastMatchingItemGroup = FindExistingUniformItemGroupWithCondition(root, projectItemElementType, framework);

            if (lastMatchingItemGroup != null)
            {
                return(lastMatchingItemGroup);
            }

            ProjectItemGroupElement ret = root.CreateItemGroupElement();
            string condStr;

            if (TryGetFrameworkConditionString(framework, out condStr))
            {
                ret.Condition = condStr;
            }

            root.InsertAfterChild(ret, root.LastItemGroup());
            return(ret);
        }
Esempio n. 10
0
        public async Task SetExplicitSdkImportsIfNecessaryAsync(string filePath)
        {
            XDocument xdoc = XDocument.Load(filePath);

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (xdoc.Root.HasAttributes && xdoc.Root.Attribute("Sdk") != null)
            {
                xdoc.Root.Attribute("Sdk").Remove();
                xdoc.Save(filePath);

                ProjectRootElement   root                  = ProjectRootElement.Open(filePath, ProjectCollection, true);
                ProjectElement       firstChild            = root.FirstChild;
                ProjectElement       lastChild             = root.LastChild;
                ProjectImportElement sdkPropsImportElement = root.CreateImportElement("Sdk.props");
                sdkPropsImportElement.Sdk = "Microsoft.NET.Sdk";
                ProjectImportElement sdkTargetsImportElement = root.CreateImportElement("Sdk.targets");
                sdkTargetsImportElement.Sdk = "Microsoft.NET.Sdk";
                root.InsertBeforeChild(sdkPropsImportElement, firstChild);
                root.InsertAfterChild(sdkTargetsImportElement, lastChild);
                root.Save(filePath);
            }
        }
        /// <summary>
        /// Creates an MSBuild properties file that specifies the full closure of packages with locked versions.
        /// </summary>
        /// <returns>A <see cref="ProjectRootElement"/> object that can be saved.</returns>
        internal bool TryCreateProject(out ProjectRootElement project)
        {
            project = null;

            if (!File.Exists(ProjectAssetsFile))
            {
                Log.LogError($"NuGet assets file '{ProjectAssetsFile}' does not exist.");
                return(false);
            }

            // should item group be conditioned or items or metadata?  Perhaps item condition should be considered and compared as well as an item could be conditioned.  Consider the below scenarios.  Since we are only parsing the assets file we need to consider the project file entries.
            // <PackageReference Include="foo" Version="1.2.3" Condition="bar"/>
            // <PackageReference Include="foo">
            //    <version>1.2.3</version>
            //    <version Condition="bar">1.2.3</version>
            // </PackageReference>
            // What about dependencies of packages that are conditioned? they should be conditioned as well.

            HashSet <string> packagesToExclude = new HashSet <string>(PackagesToExclude?.Select(i => i.ItemSpec).Distinct() ?? Enumerable.Empty <string>(), StringComparer.OrdinalIgnoreCase);

            project = ProjectRootElement.Create();

            project.ToolsVersion = String.Empty;

            ProjectPropertyElement wasImportedPropertyElement = project.AddProperty("NuGetDeterministicPropsWasImported", "true");

            LockFile lockFile = LockFileUtilities.GetLockFile(ProjectAssetsFile, NullLogger.Instance);

            bool crossTargeting = lockFile.PackageSpec.TargetFrameworks.Count > 1;

            foreach (TargetFrameworkInformation targetFramework in lockFile.PackageSpec.TargetFrameworks)
            {
                HashSet <LockFileLibrary> addedLibraries = new HashSet <LockFileLibrary>();

                ProjectItemGroupElement itemGroupElement = project.AddItemGroup();

                if (crossTargeting)
                {
                    itemGroupElement.Condition = $" '$(TargetFramework)' == '{targetFramework.FrameworkName.GetShortFolderName()}' ";
                }

                LockFileTarget target = lockFile.GetTarget(targetFramework.FrameworkName, runtimeIdentifier: null);

                bool addedImplicitReference = false;

                foreach (LibraryDependency libraryDependency in targetFramework.Dependencies.Where(i => !packagesToExclude.Contains(i.Name)))
                {
                    if (libraryDependency.AutoReferenced)
                    {
                        if (ExcludeImplicitReferences)
                        {
                            continue;
                        }
                        addedImplicitReference = true;
                    }

                    LockFileLibrary library = lockFile.GetLibrary(libraryDependency);

                    if (library.Type.Equals("project", StringComparison.OrdinalIgnoreCase))
                    {
                        // if a csproj name matches a package id then nuget swaps in the csproj output instead of the package.  Because of this we should skip adding the package as a locked package because it provides no value.
                        continue;
                    }

                    if (addedLibraries.Contains(library))
                    {
                        continue;
                    }

                    addedLibraries.Add(library);

                    LockFileTargetLibrary targetLibrary = target.GetTargetLibrary(libraryDependency.Name);

                    itemGroupElement.AddItem("PackageReference", targetLibrary.Name, GetPackageReferenceItemMetadata(library, libraryDependency));

                    foreach (LockFileLibrary dependency in targetLibrary.ResolveDependencies(lockFile, target).Where(i => !addedLibraries.Contains(i) && !packagesToExclude.Contains(i.Name)))
                    {
                        addedLibraries.Add(dependency);

                        itemGroupElement.AddItem("PackageReference", dependency.Name, GetPackageReferenceItemMetadata(dependency));
                    }
                }

                if (addedImplicitReference)
                {
                    ProjectPropertyElement disableImplicitFrameworkReferencesPropertyElement = project.AddProperty("DisableImplicitFrameworkReferences", "true");

                    if (crossTargeting)
                    {
                        disableImplicitFrameworkReferencesPropertyElement.Condition = $" '$(TargetFramework)' == '{targetFramework.FrameworkName.GetShortFolderName()}' ";
                    }
                }
            }

            ProjectImportElement beforeImportElement = project.CreateImportElement("Before.$(MSBuildThisFile)");

            project.InsertAfterChild(beforeImportElement, wasImportedPropertyElement.Parent);
            beforeImportElement.Condition = $"Exists('{beforeImportElement.Project}')";

            ProjectImportElement afterImportElement = project.AddImport("After.$(MSBuildThisFile)");

            afterImportElement.Condition = $"Exists('{afterImportElement.Project}')";

            return(true);
        }