Ejemplo n.º 1
0
        public async Task CreateInMemoryImport()
        {
            if (_unloadCancellationToken.IsCancellationRequested)
            {
                return;
            }

            using (var access = await _projectLockService.WriteLockAsync(_unloadCancellationToken)) {
                // A bit odd but we have to "check it out" prior to creating it to avoid some of the validations in chk CPS
                await access.CheckoutAsync(_inMemoryImportFullPath);

                // Now either open or create the in-memory file. Normally Create will happen, but in
                // a scenario where your project had previously failed to load for some reason, need to TryOpen
                // to avoid a new reason for a project load failure
                _inMemoryImport = ProjectRootElement.TryOpen(_inMemoryImportFullPath, access.ProjectCollection);
                if (_inMemoryImport != null)
                {
                    // The file already exists. Scrape it out so we don’t add duplicate items.
                    _inMemoryImport.RemoveAllChildren();
                }
                else
                {
                    // The project didn’t already exist, so create it, and then mark the evaluated project dirty
                    // so that MSBuild will notice. This step isn’t necessary if the project was already in memory.
                    _inMemoryImport = CreateEmptyMsBuildProject(_inMemoryImportFullPath, access.ProjectCollection);

                    // Note that we actually need to mark every project evaluation dirty that is already loaded.
                    await ReevaluateLoadedConfiguredProjects(_unloadCancellationToken, access);
                }

                _filesItemGroup          = _inMemoryImport.AddItemGroup();
                _directoriesItemGroup    = _inMemoryImport.AddItemGroup();
                _temporaryAddedItemGroup = _inMemoryImport.AddItemGroup();
            }
        }
Ejemplo n.º 2
0
        private bool TryWriteProjectsFile(ProjectCollection projectCollection, FileInfo projectsFile)
        {
            Log.LogMessageFromText($"Generating file '{projectsFile.FullName}'", MessageImportance.Low);

            Directory.CreateDirectory(projectsFile.DirectoryName);

            ProjectRootElement rootElement = ProjectRootElement.Create(projectsFile.FullName);

            ProjectItemGroupElement projectFileItemGroup   = rootElement.AddItemGroup();
            ProjectItemGroupElement traversalFileItemGroup = rootElement.AddItemGroup();

            foreach (Project project in projectCollection.LoadedProjects)
            {
                if (String.Equals(project.GetPropertyValue("IsTraversal"), "true", StringComparison.OrdinalIgnoreCase))
                {
                    traversalFileItemGroup.AddItem("TraversalFile", project.FullPath);
                }
                else
                {
                    projectFileItemGroup.AddItem("ProjectFile", project.FullPath);
                }
            }

            rootElement.Save();

            return(true);
        }
        public virtual ProjectRootElement Construct()
        {
            // Workaround for https://github.com/dotnet/msbuild/issues/2554 when using Microsoft.Build.Construction.ProjectRootElement.Create
            var msbuildExePathVarName = "MSBUILD_EXE_PATH";

            if (!Builder.UseDotNet && !TestEnvironment.IsWindows)
            {
                Environment.SetEnvironmentVariable(msbuildExePathVarName, typeof(DotNetXamarinProject).Assembly.Location);
            }
            ProjectRootElement root = null;

            try {
                root = ProjectRootElement.Create();
            } finally {
                if (!Builder.UseDotNet && !TestEnvironment.IsWindows)
                {
                    Environment.SetEnvironmentVariable(msbuildExePathVarName, null);
                }
            }

            if (Packages.Any())
            {
                root.AddItemGroup().AddItem(BuildActions.None, "packages.config");
            }
            foreach (var pkg in Packages.Where(p => p.AutoAddReferences))
            {
                foreach (var reference in pkg.References)
                {
                    if (!References.Any(r => r.Include == reference.Include))
                    {
                        References.Add(reference);
                    }
                }
            }

            foreach (var pg in PropertyGroups)
            {
                pg.AddElement(root);
            }

            foreach (var ig in ItemGroupList)
            {
                var ige = root.AddItemGroup();
                foreach (var i in ig)
                {
                    if (i.Deleted)
                    {
                        continue;
                    }
                    ige.AddItem(i.BuildAction, i.Include(), i.Metadata);
                }
            }

            root.FullPath = ProjectName + Language.DefaultProjectExtension;

            return(root);
        }
Ejemplo n.º 4
0
        public void ProjectFinishedGenerating(Project project)
        {
            string      PERSISTANCE_FOLDER = "Persistance";
            ProjectItem modelsFolder       = Utils.GetProjectItemFolder(project, PERSISTANCE_FOLDER)
                                             .FirstOrDefault();

            List <string> projectNames = Utils.GetProjectNameFromDTE(project);

            if (projectNames.Count() > 0)
            {
                frmAddProjectsRef addPrjRef = new frmAddProjectsRef(projectNames);

                System.Windows.Forms.DialogResult settingResult = addPrjRef.ShowDialog();

                IEnumerable <string> selectedProjectNames = frmAddProjectsRef.GetSelectCheckListBox.SelectedItems.OfType <string>().ToArray();

                ProjectRootElement projectRoot = ProjectRootElement.Open(project.FullName);

                foreach (var selectedPrjName in selectedProjectNames)
                {
                    if (selectedPrjName != project.Name)
                    {
                        ProjectItemGroupElement projectGroup01 = projectRoot.AddItemGroup();
                        projectGroup01.AddItem("ProjectReference", $"..\\{selectedPrjName}\\{selectedPrjName}.csproj");
                    }
                }

                projectRoot.Save();
            }

            // 2020/10/12 後修正為最後才產生 ApplicationDbContext 物件
            Utils.CreateDbContextFromSourceTables(project, modelsFolder, projectNames);
        }
Ejemplo n.º 5
0
        private void AddDefaultItemsToProject(
            SerializableMigrationDefaultsInfo defaults,
            ProjectRootElement project,
            Dictionary <string, ProjectItemGroupElement> defaultsItemGroups)
        {
            foreach (var itemInfo in defaults.Items)
            {
                ProjectItemGroupElement itemGroup;
                var parentCondition = itemInfo.ParentCondition ?? string.Empty;

                if (!defaultsItemGroups.TryGetValue(parentCondition, out itemGroup))
                {
                    itemGroup           = project.AddItemGroup();
                    itemGroup.Label     = c_DefaultsProjectElementContainerLabel;
                    itemGroup.Condition = parentCondition;

                    defaultsItemGroups[parentCondition] = itemGroup;
                }

                var item = itemGroup.AddItem(itemInfo.ItemType, itemInfo.Include);
                item.Exclude   = itemInfo.Exclude;
                item.Remove    = itemInfo.Remove;
                item.Condition = itemInfo.Condition;
            }
        }
Ejemplo n.º 6
0
        public void FindItems()
        {
            ProjectRootElement      projectRootElement = ProjectRootElement.Create();
            ProjectItemGroupElement itemGroup          = projectRootElement.AddItemGroup();

            itemGroup.AddItem(AnalyzerItemsPredictor.AnalyzerItemName, "Foo.dll");
            itemGroup.AddItem(AnalyzerItemsPredictor.AnalyzerItemName, "Bar.dll");
            itemGroup.AddItem(AnalyzerItemsPredictor.AnalyzerItemName, "Baz.dll");
            ProjectInstance projectInstance = TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement);

            var expectedInputFiles = new[]
            {
                new PredictedItem("Foo.dll", nameof(AnalyzerItemsPredictor)),
                new PredictedItem("Bar.dll", nameof(AnalyzerItemsPredictor)),
                new PredictedItem("Baz.dll", nameof(AnalyzerItemsPredictor)),
            };

            new AnalyzerItemsPredictor()
            .GetProjectPredictions(projectInstance)
            .AssertPredictions(
                projectInstance,
                expectedInputFiles,
                null,
                null,
                null);
        }
Ejemplo n.º 7
0
        private void MigrateProjectJsonProjectDependency(
            Project project,
            NuGetFramework framework,
            HashSet <string> migratedXProjDependencyNames,
            SlnFile solutionFile,
            ProjectRootElement outputMSBuildProject)
        {
            var projectDependencies = _projectDependencyFinder.ResolveAllProjectDependenciesForFramework(
                new ProjectDependency(project.Name, project.ProjectFilePath, false),
                framework,
                migratedXProjDependencyNames,
                solutionFile);

            var projectDependencyTransformResults =
                projectDependencies.Select(p =>
                                           p.Hoisted ?
                                           HoistedDependencyTransform.Transform(p) :
                                           ProjectDependencyTransform.Transform(p));

            if (projectDependencyTransformResults.Any())
            {
                AddProjectDependenciesToNewItemGroup(
                    outputMSBuildProject.AddItemGroup(),
                    projectDependencyTransformResults,
                    framework);
            }

            HoistFrameworkAssembliesForProjectDependencies(projectDependencies, outputMSBuildProject);
        }
Ejemplo n.º 8
0
            private ProjectRootElement CreateProject()
            {
                Microsoft.Build.Evaluation.Project project = null;
                try
                {
                    project = Microsoft.Expression.Project.Build.BuildManager.GetProject(DocumentReference.Create(this.originalProjectFilePath));
                }
                catch (ArgumentException argumentException)
                {
                }
                ProjectRootElement projectRootElement = ProjectRootElement.Create();

                projectRootElement.ToolsVersion = "4.0";
                this.AddBuildProperties(projectRootElement, project);
                projectRootElement.AddItemGroup();
                projectRootElement.AddPropertyGroup();
                projectRootElement.AddProperty("IntermediateOutputPath", Microsoft.Expression.Framework.Documents.PathHelper.GetDirectoryNameOrRoot(this.xamlPath));
                this.AddAssemblyReferences(projectRootElement, project);
                this.AddImports(projectRootElement, project);
                if (!this.IsSilverlightApplication(project))
                {
                    this.AddWpfImports(projectRootElement);
                }
                projectRootElement.AddItem("Page", this.xamlPath);
                string str = Microsoft.Expression.Framework.Documents.PathHelper.ResolveCombinedPath(Microsoft.Expression.Framework.Documents.PathHelper.GetDirectoryNameOrRoot(this.xamlPath), "MarkupCompileAssembly.proj");

                projectRootElement.Save(str);
                return(projectRootElement);
            }
Ejemplo n.º 9
0
        private static void ReferenceProject(ProjectRootElement referenced, ProjectRootElement referencing)
        {
            //get project references
            const string itemType   = "ProjectReference";
            var          references = referencing.ItemGroups.FirstOrDefault(g => g.Items.All(i => i.ItemType == itemType)) ??
                                      referencing.AddItemGroup();

            var referencedPath        = new Uri(referenced.FullPath, UriKind.Absolute);
            var referencingPathString = (Path.GetDirectoryName(referencing.FullPath) ?? "") +
                                        Path.DirectorySeparatorChar;
            var referencingPath = new Uri(referencingPathString, UriKind.Absolute);

            var relPath = referencingPath.MakeRelativeUri(referencedPath).ToString();

            //check if it is not there already
            if (references.Children.Any(c =>
            {
                var itemElement = c as ProjectItemElement;
                return(itemElement != null && itemElement.Include == relPath);
            }))
            {
                return;
            }

            references.AddItem(itemType, relPath, new[]
            {
                new KeyValuePair <string, string>("Project", GetProjectId(referenced)),
                new KeyValuePair <string, string>("Name", Path.GetFileNameWithoutExtension(referenced.FullPath))
            });
        }
Ejemplo n.º 10
0
        private static ProjectInstance CreateTestProjectInstance(string fileName, bool hasProjectReferences = true, bool isEnabled = true)
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create($@"ServiceFabricApp\{fileName}");

            // These are generally set in Microsoft.VisualStudio.Azure.Fabric.Application.targets
            ProjectPropertyGroupElement propertyGroup = projectRootElement.AddPropertyGroup();

            propertyGroup.AddProperty(ServiceFabricServiceManifestPredictor.ApplicationPackageRootFolderPropertyName, "ApplicationPackageRoot");
            propertyGroup.AddProperty(ServiceFabricServiceManifestPredictor.ServicePackageRootFolderPropertyName, "PackageRoot");
            if (isEnabled)
            {
                propertyGroup.AddProperty(ServiceFabricServiceManifestPredictor.UpdateServiceFabricApplicationManifestEnabledPropertyName, "true");
            }

            if (hasProjectReferences)
            {
                ProjectItemGroupElement itemGroup = projectRootElement.AddItemGroup();
                itemGroup.AddItem(ServiceFabricServiceManifestPredictor.ProjectReferenceItemName, @"..\Service1\Service1.csproj");
                itemGroup.AddItem(ServiceFabricServiceManifestPredictor.ProjectReferenceItemName, @"..\Service2\Service2.csproj");
            }

            // Extra service manifests, and some extraneous files too
            Directory.CreateDirectory(@"ServiceFabricApp\ApplicationPackageRoot");
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\{ServiceFabricServiceManifestPredictor.ServiceManifestFileName}", "SomeContent"); // Not in a subdir, should not get picked up
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\extraneous.txt", "SomeContent");
            Directory.CreateDirectory(@"ServiceFabricApp\ApplicationPackageRoot\Foo");
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\Foo\{ServiceFabricServiceManifestPredictor.ServiceManifestFileName}", "SomeContent");
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\Foo\extraneous.txt", "SomeContent");
            Directory.CreateDirectory(@"ServiceFabricApp\ApplicationPackageRoot\Bar");
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\Bar\{ServiceFabricServiceManifestPredictor.ServiceManifestFileName}", "SomeContent");
            File.WriteAllText($@"ServiceFabricApp\ApplicationPackageRoot\Bar\extraneous.txt", "SomeContent");

            return(TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement));
        }
        private void ReplaceReferences(ProjectRootElement project, List <PackageIdentity> packages, ProjectRootElement packagesProps)
        {
            HashSet <PackageIdentity> allPackages = new HashSet <PackageIdentity>(packages);

            Dictionary <ProjectItemElement, PackageIdentity> itemsToReplace = new Dictionary <ProjectItemElement, PackageIdentity>();

            foreach (ProjectItemElement itemElement in project.Items.Where(i => i.ItemType.Equals("Reference")))
            {
                foreach (PackageIdentity packageIdentity in packages)
                {
                    Regex regex = AssemblyReferenceRegularExpressions[packageIdentity];

                    ProjectMetadataElement metadatum = itemElement.Metadata.FirstOrDefault(i => i.Name.Equals("HintPath"));

                    if (metadatum != null && regex.IsMatch(metadatum.Value))
                    {
                        itemsToReplace.Add(itemElement, packageIdentity);

                        allPackages.Remove(packageIdentity);
                    }
                }
            }

            List <PackageIdentity> packagesAdded = new List <PackageIdentity>();

            ProjectItemElement      firstPackageRef = project.Items.FirstOrDefault(i => i.ItemType.Equals("PackageReference"));
            ProjectItemGroupElement packageRefsGroup;

            if (firstPackageRef == null)
            {
                packageRefsGroup = project.AddItemGroup();
            }
            else
            {
                packageRefsGroup = (ProjectItemGroupElement)firstPackageRef.Parent;
            }

            foreach (KeyValuePair <ProjectItemElement, PackageIdentity> pair in itemsToReplace)
            {
                if (!packagesAdded.Contains(pair.Value))
                {
                    ProjectItemElement item = project.CreateItemElement("PackageReference", pair.Value.Id);

                    packageRefsGroup.AddItem("PackageReference", pair.Value.Id);

                    SetPackageVersion(item, pair.Value.Version, packagesProps);

                    packagesAdded.Add(pair.Value);
                }

                pair.Key.Parent.RemoveChild(pair.Key);
            }

            foreach (PackageIdentity package in allPackages)
            {
                ProjectItemElement item = packageRefsGroup.AddItem("PackageReference", package.Id);
                SetPackageVersion(item, package.Version, packagesProps);
            }
        }
        private void MigrateDependencies(
            Project project,
            ProjectRootElement output,
            NuGetFramework framework,
            IEnumerable <ProjectLibraryDependency> dependencies,
            ProjectRootElement xproj,
            SlnFile solutionFile,
            ProjectItemGroupElement itemGroup = null)
        {
            var projectDependencies = new HashSet <string>(GetAllProjectReferenceNames(project, framework, xproj, solutionFile));
            var packageDependencies = dependencies.Where(d => !projectDependencies.Contains(d.Name)).ToList();

            string condition = framework?.GetMSBuildCondition() ?? "";

            itemGroup = itemGroup
                        ?? output.ItemGroups.FirstOrDefault(i => i.Condition == condition)
                        ?? output.AddItemGroup();
            itemGroup.Condition = condition;

            AutoInjectImplicitProjectJsonAssemblyReferences(framework, packageDependencies);

            foreach (var packageDependency in packageDependencies)
            {
                MigrationTrace.Instance.WriteLine(packageDependency.Name);
                AddItemTransform <PackageDependencyInfo> transform;

                if (packageDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Reference)
                {
                    transform = FrameworkDependencyTransform;
                }
                else
                {
                    transform = PackageDependencyInfoTransform();
                    if (packageDependency.Type.Equals(LibraryDependencyType.Build))
                    {
                        transform = transform.WithMetadata("PrivateAssets", "All");
                    }
                    else if (packageDependency.SuppressParent != LibraryIncludeFlagUtils.DefaultSuppressParent)
                    {
                        var metadataValue = ReadLibraryIncludeFlags(packageDependency.SuppressParent);
                        transform = transform.WithMetadata("PrivateAssets", metadataValue);
                    }

                    if (packageDependency.IncludeType != LibraryIncludeFlags.All)
                    {
                        var metadataValue = ReadLibraryIncludeFlags(packageDependency.IncludeType);
                        transform = transform.WithMetadata("IncludeAssets", metadataValue);
                    }
                }

                _transformApplicator.Execute(
                    transform.Transform(ToPackageDependencyInfo(
                                            packageDependency,
                                            PackageConstants.ProjectDependencyPackages)),
                    itemGroup,
                    mergeExisting: true);
            }
        }
Ejemplo n.º 13
0
        private static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
        {
            var group = elem.AddItemGroup();

            foreach (var item in items)
            {
                group.AddItem(groupName, item);
            }
        }
Ejemplo n.º 14
0
        private static ProjectInstance CreateTestProjectInstance(string fileName)
        {
            ProjectRootElement      projectRootElement = ProjectRootElement.Create(fileName);
            ProjectItemGroupElement itemGroup          = projectRootElement.AddItemGroup();

            itemGroup.AddItem(AzureCloudServicePredictor.ServiceDefinitionItemName, "ServiceDefinition.csdef");
            itemGroup.AddItem(AzureCloudServicePredictor.ServiceConfigurationItemName, "ServiceConfiguration.Local.cscfg");
            itemGroup.AddItem(AzureCloudServicePredictor.ServiceConfigurationItemName, "ServiceConfiguration.Prod.cscfg");

            return(TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement));
        }
        public static ProjectRootElement AddPackageVersion(this ProjectRootElement element, string packageName,
                                                           string version)
        {
            var itemGroup = element.ItemGroups.FirstOrDefault() ?? element.AddItemGroup();

            var item = itemGroup.AddItem("PackageVersion", packageName);

            item.AddMetadata("Version", version, expressAsAttribute: true);

            return(element);
        }
Ejemplo n.º 16
0
        private void UpdateCSProjectFolders(ProjectRootElement projectRoot)
        {
            var    deletePhysicalName = projectRoot.FullPath; //deleteItem.Properties.Item("FullPath");
            string fullPath           = deletePhysicalName;
            string projectPath        = Path.GetDirectoryName(fullPath);

            ProjectItemGroupElement group01 = null;

            if (Directory.Exists(Path.Combine(projectPath, "Models")))
            {
                group01 = group01 ?? projectRoot.AddItemGroup();
                group01.AddItem("Folder", @"Models\");
            }

            if (Directory.Exists(Path.Combine(projectPath, "Views")))
            {
                group01 = group01 ?? projectRoot.AddItemGroup();
                group01.AddItem("Folder", @"Views\");
            }
        }
        public void Generate(string outputPath, string propertyVersionNamePrefix, string propertyPathNamePrefix, PackageRestoreData restoreData)
        {
            // Delete an existing file in case there are no properties generated and we don't end up saving the file
            //
            if (File.Exists(outputPath))
            {
                Retry(() => File.Delete(outputPath), TimeSpan.FromMilliseconds(500));
            }

            ProjectRootElement          project       = ProjectRootElement.Create();
            ProjectPropertyGroupElement propertyGroup = project.AddPropertyGroup();

            propertyGroup.SetProperty("MSBuildAllProjects", "$(MSBuildAllProjects);$(MSBuildThisFileFullPath)");

            ProjectItemGroupElement itemGroup = project.AddItemGroup();

            bool anyPropertiesCreated = false;

            foreach (string packageConfigPath in _packageConfigPaths)
            {
                _logger.LogMessage(MessageImportance.Low, $"Parsing '{packageConfigPath}'");

                IEnumerable <PackageIdentityWithPath> parsedPackages = null;

                INuGetPackageConfigParser configParser = null;

                // A bug in nuget sometimes causes "NuGet.Configuration.NuGetConfigurationException: Unexpected failure reading NuGet.Config." when multiple instances are running in parrallel such as in the quickbuild scenario.
                Retry(() => configParser = _configParsersLazy.Value.FirstOrDefault(i => i.TryGetPackages(packageConfigPath, restoreData, out parsedPackages)), TimeSpan.FromMilliseconds(1000));

                if (configParser != null && parsedPackages != null)
                {
                    anyPropertiesCreated = true;

                    foreach (PackageIdentityWithPath packageInfo in parsedPackages)
                    {
                        propertyGroup.SetProperty($"{propertyPathNamePrefix}{packageInfo.Id.Replace(".", "_")}", $"{packageInfo.FullPath}");

                        propertyGroup.SetProperty($"{propertyVersionNamePrefix}{packageInfo.Id.Replace(".", "_")}", $"{packageInfo.Version.ToString()}");

                        // Consider adding item metadata of packageid and version for ease of consumption of this property.
                        itemGroup.AddItem("CBTNuGetPackageDir", packageInfo.FullPath);
                    }
                }
            }

            // Don't save the file if no properties were created.  In Visual Studio design time builds, this can be called multiple times until there are finally
            // properties that can be created.  If we generate an empty file, it won't get regenerated once there are properties to create.
            //
            if (anyPropertiesCreated)
            {
                Retry(() => project.Save(outputPath), TimeSpan.FromMilliseconds(500));
            }
        }
        private static Project CreateTestProject(params string[] compileItemIncludes)
        {
            ProjectRootElement      projectRootElement = ProjectRootElement.Create();
            ProjectItemGroupElement itemGroup          = projectRootElement.AddItemGroup();

            foreach (string compileItemInclude in compileItemIncludes)
            {
                itemGroup.AddItem("Compile", compileItemInclude);
            }

            return(TestHelpers.CreateProjectFromRootElement(projectRootElement));
        }
Ejemplo n.º 19
0
        private static ProjectInstance CreateTestProjectInstance(IEnumerable <string> availableItemNames, params Tuple <string, string>[] itemNamesAndValues)
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create();

            // Add Items.
            ProjectItemGroupElement itemGroup = projectRootElement.AddItemGroup();

            foreach (Tuple <string, string> itemNameAndValue in itemNamesAndValues)
            {
                itemGroup.AddItem(itemNameAndValue.Item1, itemNameAndValue.Item2);
            }

            // Add AvailableItemName items referring to the item names we'll add soon.
            ProjectItemGroupElement namesItemGroup = projectRootElement.AddItemGroup();

            foreach (string availableItemName in availableItemNames)
            {
                namesItemGroup.AddItem(AvailableItemNameItemsPredictor.AvailableItemName, availableItemName);
            }

            return(TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Adds the item group containting the ProjectConfiguration items to a new project.
        /// </summary>
        void AddProjectConfigurationsItemGroup()
        {
            ProjectRootElement      file            = MSBuildProjectFile;
            ProjectItemGroupElement configItemGroup = file.AddItemGroup();

            configItemGroup.Label = "ProjectConfigurations";
            foreach (var target in new [] { new ConfigurationAndPlatform("Debug", "Win32"), new ConfigurationAndPlatform("Release", "Win32") })
            {
                ProjectItemElement prjConfiguration = configItemGroup.AddItem("ProjectConfiguration", target.ToString());
                prjConfiguration.AddMetadata("Configuration", target.Configuration);
                prjConfiguration.AddMetadata("Platform", target.Platform);
            }
        }
Ejemplo n.º 21
0
        static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
        {
            ProjectItemGroupElement group = elem.AddItemGroup();

            foreach (var item in items)
            {
                ProjectItemElement projItem = group.AddItem(groupName, item);
                //if (groupName == "Compile")
                //{
                //    projItem.AddMetadata("Link", item);
                //}
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Adds the item group containting the ProjectConfiguration items to a new project.
        /// </summary>
        void AddProjectConfigurationsItemGroup()
        {
            ProjectRootElement      file            = MSBuildProjectFile;
            ProjectItemGroupElement configItemGroup = file.AddItemGroup();

            configItemGroup.Label = "ProjectConfigurations";
            foreach (string target in new string[] { "Debug|Win32", "Release|Win32" })
            {
                ProjectItemElement prjConfiguration = configItemGroup.AddItem("ProjectConfiguration", target);
                prjConfiguration.AddMetadata("Configuration", GetConfigurationNameFromKey(target));
                prjConfiguration.AddMetadata("Platform", GetPlatformNameFromKey(target));
            }
        }
Ejemplo n.º 23
0
        public void SetCondition()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            project.AddItemGroup();
            Helpers.ClearDirtyFlag(project);

            ProjectItemGroupElement itemGroup = Helpers.GetFirst(project.ItemGroups);

            itemGroup.Condition = "c";

            Assert.AreEqual("c", itemGroup.Condition);
            Assert.AreEqual(true, project.HasUnsavedChanges);
        }
Ejemplo n.º 24
0
        public void SetLabel()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            project.AddItemGroup();
            Helpers.ClearDirtyFlag(project);

            ProjectItemGroupElement itemGroup = Helpers.GetFirst(project.ItemGroups);

            itemGroup.Label = "c";

            Assert.Equal("c", itemGroup.Label);
            Assert.True(project.HasUnsavedChanges);
        }
Ejemplo n.º 25
0
        public RepositoryProject(string repositoryRoot)
        {
            _doc = ProjectRootElement.Create(NewProjectFileOptions.None);
            var import    = _doc.CreateImportElement(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
            var propGroup = _doc.AddPropertyGroup();

            if (repositoryRoot[repositoryRoot.Length - 1] != '\\')
            {
                repositoryRoot += '\\';
            }
            propGroup.AddProperty("RepositoryRoot", repositoryRoot);
            _doc.AddItemGroup();
            _doc.PrependChild(import);
            _doc.AddImport(@"$(MSBuildToolsPath)\Microsoft.Common.targets");
        }
Ejemplo n.º 26
0
    private string GenerateBootstrapper(string manifestFile, string applicationName, string applicationUrl, params string[] prerequisites)
    {
        // root element
        ProjectRootElement xml = ProjectRootElement.Create();

        xml.ToolsVersion   = "4.0";
        xml.DefaultTargets = "BuildBootstrapper";
        // build properties
        var propertyGroup = xml.AddPropertyGroup();

        propertyGroup.AddProperty("TargetFrameworkVersion", "v4.5");
        propertyGroup.AddProperty("VisualStudioVersion", "11.0");
        // prerequisites (product codes of each required package, e.g. ".NETFramework,Version=v4.5")
        var itemGroup = xml.AddItemGroup();

        foreach (string productCode in prerequisites)
        {
            itemGroup.AddItem("BootstrapperFile", productCode);
        }
        // target
        var target = xml.AddTarget("BuildBootstrapper");
        var task   = target.AddTask("GenerateBootstrapper");

        task.SetParameter("ApplicationFile", Path.GetFileName(manifestFile));
        task.SetParameter("ApplicationName", applicationName);
        task.SetParameter("ApplicationUrl", applicationUrl);
        task.SetParameter("BootstrapperItems", "@(BootstrapperFile)");
        task.SetParameter("OutputPath", Path.GetDirectoryName(manifestFile));
        task.SetParameter("Path", @"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\Bootstrapper");         // replace with actual path
        var proj       = new ProjectInstance(xml);
        var req        = new BuildRequestData(proj, new string[] { "BuildBootstrapper" });
        var parameters = new BuildParameters();
        // optional logging of the build process
        var logger   = new FileLogger();
        Uri codeBase = new Uri(Assembly.GetEntryAssembly().CodeBase);

        logger.Parameters  = "logfile=" + Path.Combine(Path.GetDirectoryName(codeBase.LocalPath), "msbuild.log");
        parameters.Loggers = new ILogger[] { logger };
        // build the bootstrapper executable (setup.exe)
        var result = BuildManager.DefaultBuildManager.Build(parameters, req);

        if (result.OverallResult == BuildResultCode.Failure)
        {
            throw new InvalidOperationException("MSBuild task failed!", result.Exception);
        }
        // return path to the built setup.exe
        return(Path.Combine(Path.GetDirectoryName(manifestFile), "setup.exe"));
    }
Ejemplo n.º 27
0
        private void MigrateDependencies(
            Project project,
            ProjectRootElement output,
            NuGetFramework framework,
            IEnumerable <ProjectLibraryDependency> dependencies,
            ProjectRootElement xproj)
        {
            var projectDependencies = new HashSet <string>(GetAllProjectReferenceNames(project, framework, xproj));
            var packageDependencies = dependencies.Where(d => !projectDependencies.Contains(d.Name));

            string condition = framework?.GetMSBuildCondition() ?? "";
            var    itemGroup = output.ItemGroups.FirstOrDefault(i => i.Condition == condition)
                               ?? output.AddItemGroup();

            itemGroup.Condition = condition;

            foreach (var packageDependency in packageDependencies)
            {
                MigrationTrace.Instance.WriteLine(packageDependency.Name);
                AddItemTransform <ProjectLibraryDependency> transform;

                if (packageDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Reference)
                {
                    transform = FrameworkDependencyTransform;
                }
                else
                {
                    transform = PackageDependencyTransform();
                    if (packageDependency.Type == LibraryDependencyType.Build)
                    {
                        transform = transform.WithMetadata("PrivateAssets", "all");
                    }
                    else if (packageDependency.SuppressParent != LibraryIncludeFlagUtils.DefaultSuppressParent)
                    {
                        var metadataValue = ReadLibraryIncludeFlags(packageDependency.SuppressParent);
                        transform = transform.WithMetadata("PrivateAssets", metadataValue);
                    }

                    if (packageDependency.IncludeType != LibraryIncludeFlags.All)
                    {
                        var metadataValue = ReadLibraryIncludeFlags(packageDependency.IncludeType);
                        transform = transform.WithMetadata("IncludeAssets", metadataValue);
                    }
                }

                _transformApplicator.Execute(transform.Transform(packageDependency), itemGroup);
            }
        }
Ejemplo n.º 28
0
        public void SettingItemUpdateDirties()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            ProjectItemElement item = project.AddItemGroup().AddItem("i", "i1");

            item.Include = null;
            Helpers.ClearDirtyFlag(project);

            Assert.False(project.HasUnsavedChanges);

            item.Update = "i2";

            Assert.Equal("i2", item.Update);
            Assert.True(project.HasUnsavedChanges);
        }
        private void MigrateTools(
            Project project,
            ProjectRootElement output)
        {
            if (project.Tools == null || !project.Tools.Any())
            {
                return;
            }

            var itemGroup = output.AddItemGroup();

            foreach (var tool in project.Tools)
            {
                _transformApplicator.Execute(ToolTransform.Transform(tool), itemGroup, mergeExisting: true);
            }
        }
        public GivenThatIWantToMigrateAssemblyInfo()
        {
            var projectDirectory =
                TestAssetsManager.CreateTestInstance("AppWithAssemblyInfo").Path;
            var projectContext =
                ProjectContext.Create(projectDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            _mockProject = ProjectRootElement.Create();
            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(projectDirectory, projectDirectory, _mockProject, null);
            var testInputs   = new MigrationRuleInputs(
                new[] { projectContext },
                _mockProject,
                _mockProject.AddItemGroup(),
                _mockProject.AddPropertyGroup());

            new MigrateAssemblyInfoRule().Apply(testSettings, testInputs);
        }