public static bool IsWindowsStoreApp(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            string[] types = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject);
            return(types.Contains(VsProjectTypes.WindowsStoreProjectTypeGuid, StringComparer.OrdinalIgnoreCase));
        }
Exemplo n.º 2
0
 private static bool IsWebProject(EnvDTE.Project envDTEProject)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     string[] types = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject);
     return(types.Contains(VsProjectTypes.WebSiteProjectTypeGuid, StringComparer.OrdinalIgnoreCase) ||
            types.Contains(VsProjectTypes.WebApplicationProjectTypeGuid, StringComparer.OrdinalIgnoreCase));
 }
        private static bool IsWebProject(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            string[] types = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject);
            return(types.Contains(VsProjectTypes.WebSiteProjectTypeGuid, StringComparer.OrdinalIgnoreCase) ||
                   types.Contains(VsProjectTypes.WebApplicationProjectTypeGuid, StringComparer.OrdinalIgnoreCase));
        }
        public static async Task <string[]> GetProjectTypeGuidsAsync(this EnvDTE.Project project)
        {
            Verify.ArgumentIsNotNull(project, nameof(project));

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            // Get the vs hierarchy as an IVsAggregatableProject to get the project type guids
            IVsHierarchy hierarchy = await ToVsHierarchyAsync(project);

            string[] projectTypeGuids = VsHierarchyUtility.GetProjectTypeGuids(hierarchy, project.Kind);

            return(projectTypeGuids);
        }
Exemplo n.º 5
0
        public static string[] GetProjectTypeGuids(this EnvDTE.Project project)
        {
            Verify.ArgumentIsNotNull(project, nameof(project));

            ThreadHelper.ThrowIfNotOnUIThread();

            // Get the vs hierarchy as an IVsAggregatableProject to get the project type guids
            IVsHierarchy hierarchy = ToVsHierarchy(project);

            string[] projectTypeGuids = VsHierarchyUtility.GetProjectTypeGuids(hierarchy, project.Kind);

            return(projectTypeGuids);
        }
Exemplo n.º 6
0
        private async Task <object> MigrateProjectToPackageRefAsync(string projectUniqueName)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var project = _solutionManager.Value.GetDTEProject(projectUniqueName);

            if (project == null)
            {
                throw new InvalidOperationException(string.Format(VsResources.Error_ProjectNotInCache, projectUniqueName));
            }

            var projectSafeName = await EnvDTEProjectInfoUtility.GetCustomUniqueNameAsync(project);

            var nuGetProject = _solutionManager.Value.GetNuGetProject(projectSafeName);

            // If the project already has PackageReference, do nothing.
            if (nuGetProject is LegacyCSProjPackageReferenceProject)
            {
                return(new VsProjectJsonToPackageReferenceMigrateResult(success: true, errorMessage: null));
            }

            try
            {
                _solutionManager.Value.SaveProject(nuGetProject);

                var legacyPackageRefBasedProject = new LegacyCSProjPackageReferenceProject(
                    new EnvDTEProjectAdapter(project),
                    VsHierarchyUtility.GetProjectId(project));

                await ProjectJsonToPackageRefMigrator.MigrateAsync(
                    legacyPackageRefBasedProject,
                    legacyPackageRefBasedProject.MSBuildProjectPath);

                var result = new VsProjectJsonToPackageReferenceMigrateResult(success: true, errorMessage: null);
                _solutionManager.Value.SaveProject(nuGetProject);
                await _solutionManager.Value.UpdateNuGetProjectToPackageRef(nuGetProject);

                return(result);
            }
            catch (Exception ex)
            {
                // reload the project in memory from the file on disk, discarding any changes that might have
                // been made as a result of an incomplete migration.
                ReloadProject(project);
                return(new VsProjectJsonToPackageReferenceMigrateResult(success: false, errorMessage: ex.Message));
            }
        }
Exemplo n.º 7
0
        private void RunJTFWithCorrectContext(Project project, Func <Task> asyncTask)
        {
            if (!_isCPSJTFLoaded)
            {
                NuGetUIThreadHelper.JoinableTaskFactory.Run(async() =>
                {
                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    IVsHierarchy vsHierarchy = await project.ToVsHierarchyAsync();
                    if (vsHierarchy != null &&
                        VsHierarchyUtility.IsCPSCapabilityCompliant(vsHierarchy))
                    {
                        // Lazy load the CPS enabled JoinableTaskFactory for the UI.
                        NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor);

                        PumpingJTF      = new PumpingJTF(NuGetUIThreadHelper.JoinableTaskFactory);
                        _isCPSJTFLoaded = true;
                    }
                });
            }

            PumpingJTF.Run(asyncTask);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Installs one or more packages into the specified project.
        /// </summary>
        /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param>
        /// <param name="project">The target project for installation.</param>
        /// <param name="configuration">
        /// The packages to install, where to install them from, and additional options for
        /// their installation.
        /// </param>
        /// <param name="repositorySettings">The repository settings for the packages being installed.</param>
        /// <param name="warningHandler">
        /// An action that accepts a warning message and presents it to the user, allowing
        /// execution to continue.
        /// </param>
        /// <param name="errorHandler">
        /// An action that accepts an error message and presents it to the user, allowing
        /// execution to continue.
        /// </param>
        internal async Task PerformPackageInstallAsync(
            IVsPackageInstaller packageInstaller,
            EnvDTE.Project project,
            PreinstalledPackageConfiguration configuration,
            Action <string> warningHandler,
            Action <string> errorHandler)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            string repositoryPath      = configuration.RepositoryPath;
            var    repositorySource    = new Configuration.PackageSource(repositoryPath);
            var    failedPackageErrors = new List <string>();

            // find the project
            var defaultProjectContext = new VSAPIProjectContext();
            var nuGetProject          = await _solutionManager.GetOrCreateProjectAsync(project, defaultProjectContext);

            // For BuildIntegratedNuGetProject, nuget will ignore preunzipped configuration.
            var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;

            var repository = (buildIntegratedProject == null && configuration.IsPreunzipped) ?
                             _sourceProvider.CreateRepository(repositorySource, FeedType.FileSystemUnzipped) :
                             _sourceProvider.CreateRepository(repositorySource);

            var repoProvider = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider);

            repoProvider.AddFromSource(repository);

            var packageManager = _installer.CreatePackageManager(repoProvider);
            var gatherCache    = new GatherCache();

            var sources = repoProvider.GetRepositories().ToList();

            // store expanded node state
            var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager);

            try
            {
                foreach (var package in configuration.Packages)
                {
                    var packageIdentity = new PackageIdentity(package.Id, package.Version);

                    // Does the project already have this package installed?
                    if (_packageServices.IsPackageInstalled(project, package.Id))
                    {
                        // If so, is it the right version?
                        if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString()))
                        {
                            // No? Raise a warning (likely written to the Output window) and ignore this package.
                            warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version));
                        }
                        // Yes? Just silently ignore this package!
                    }
                    else
                    {
                        try
                        {
                            if (InfoHandler != null)
                            {
                                InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version));
                            }

                            // Skip assembly references and disable binding redirections should be done together
                            bool disableBindingRedirects = package.SkipAssemblyReferences;

                            var projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects);

                            // Old templates have hardcoded non-normalized paths
                            projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true;

                            // This runs from the UI thread
                            await _installer.InstallInternalCoreAsync(
                                packageManager,
                                gatherCache,
                                nuGetProject,
                                packageIdentity,
                                sources,
                                projectContext,
                                includePrerelease : false,
                                ignoreDependencies : package.IgnoreDependencies,
                                token : CancellationToken.None);
                        }
                        catch (InvalidOperationException exception)
                        {
                            failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                        }
                        catch (AggregateException aggregateEx)
                        {
                            var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault();
                            if (ex is InvalidOperationException)
                            {
                                failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }

                if (failedPackageErrors.Any())
                {
                    var errorString = new StringBuilder();
                    errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath);
                    errorString.AppendLine();
                    errorString.AppendLine();
                    errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));

                    errorHandler(errorString.ToString());
                }

                // RepositorySettings = null in unit tests
                if (EnvDTEProjectInfoUtility.IsWebSite(project))
                {
                    CreateRefreshFilesInBin(
                        project,
                        repositoryPath,
                        configuration.Packages.Where(p => p.SkipAssemblyReferences));

                    CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Internal install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternalAsync(
            Project project,
            List <PackageIdentity> packages,
            ISourceRepositoryProvider repoProvider,
            VSAPIProjectContext projectContext,
            bool includePrerelease,
            bool ignoreDependencies,
            CancellationToken token)
        {
            // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary
            // This method installs multiple packages and can likely take more than a few secs
            // So, go off the UI thread explicitly to improve responsiveness
            await TaskScheduler.Default;

            var gatherCache = new GatherCache();
            var sources     = repoProvider.GetRepositories().ToList();

            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager);

            try
            {
                DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                ResolutionContext resolution = new ResolutionContext(
                    depBehavior,
                    includePrerelease,
                    includeUnlisted: false,
                    versionConstraints: VersionConstraints.None);

                var packageManager = CreatePackageManager(repoProvider);

                // find the project
                var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(project, projectContext);

                // install the package
                foreach (PackageIdentity package in packages)
                {
                    // Check if the package is already installed
                    if (package.Version == null)
                    {
                        if (_packageServices.IsPackageInstalled(project, package.Id))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToString()))
                        {
                            continue;
                        }
                    }

                    // Perform the install
                    await InstallInternalCoreAsync(
                        packageManager,
                        gatherCache,
                        nuGetProject,
                        package,
                        sources,
                        projectContext,
                        includePrerelease,
                        ignoreDependencies,
                        token);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Internal install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternalAsync(
            Project project,
            List <PackageIdentity> packages,
            ISourceRepositoryProvider repoProvider,
            VSAPIProjectContext projectContext,
            bool includePrerelease,
            bool ignoreDependencies,
            CancellationToken token)
        {
            // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary
            // This method installs multiple packages and can likely take more than a few secs
            // So, go off the UI thread explicitly to improve responsiveness
            await TaskScheduler.Default;

            var gatherCache = new GatherCache();
            var sources     = repoProvider.GetRepositories().ToList();

            // store expanded node state
            var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync();

            try
            {
                var depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                var packageManager = CreatePackageManager(repoProvider);

                // find the project
                var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(project, projectContext);

                var packageManagementFormat = new PackageManagementFormat(_settings);
                // 1 means PackageReference
                var preferPackageReference = packageManagementFormat.SelectedPackageManagementFormat == 1;

                // Check if default package format is set to `PackageReference` and project has no
                // package installed yet then upgrade it to `PackageReference` based project.
                if (preferPackageReference &&
                    (nuGetProject is MSBuildNuGetProject) &&
                    !(await nuGetProject.GetInstalledPackagesAsync(token)).Any() &&
                    await NuGetProjectUpgradeUtility.IsNuGetProjectUpgradeableAsync(nuGetProject, project, needsAPackagesConfig: false))
                {
                    nuGetProject = await _solutionManager.UpgradeProjectToPackageReferenceAsync(nuGetProject);
                }

                // install the package
                foreach (var package in packages)
                {
                    var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);

                    // Check if the package is already installed
                    if (package.Version != null &&
                        PackageServiceUtilities.IsPackageInList(installedPackageReferences, package.Id, package.Version))
                    {
                        continue;
                    }

                    // Perform the install
                    await InstallInternalCoreAsync(
                        packageManager,
                        gatherCache,
                        nuGetProject,
                        package,
                        sources,
                        projectContext,
                        includePrerelease,
                        ignoreDependencies,
                        token);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(expandedNodes);
            }
        }
Exemplo n.º 11
0
 public static bool IsWindowsStoreApp(EnvDTE.Project envDTEProject)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     string[] types = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject);
     return(types.Contains(VsProjectTypes.WindowsStoreProjectTypeGuid, StringComparer.OrdinalIgnoreCase));
 }
Exemplo n.º 12
0
 public static VsHierarchyItem FromDteProject(EnvDTE.Project project)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Assumes.Present(project);
     return(new VsHierarchyItem(VsHierarchyUtility.ToVsHierarchy(project)));
 }
        /// <summary>
        /// Core install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternalAsync(
            Project project,
            List <PackageIdentity> packages,
            ISourceRepositoryProvider repoProvider,
            VSAPIProjectContext projectContext,
            bool includePrerelease,
            bool ignoreDependencies,
            CancellationToken token)
        {
            // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary
            // This method installs multiple packages and can likely take more than a few secs
            // So, go off the UI thread explicitly to improve responsiveness
            await TaskScheduler.Default;

            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager);

            try
            {
                DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                ResolutionContext resolution = new ResolutionContext(
                    depBehavior,
                    includePrerelease,
                    includeUnlisted: false,
                    versionConstraints: VersionConstraints.None);

                NuGetPackageManager packageManager =
                    new NuGetPackageManager(
                        repoProvider,
                        _settings,
                        _solutionManager,
                        _deleteOnRestartManager);

                // find the project
                NuGetProject nuGetProject = await PackageManagementHelpers.GetProjectAsync(_solutionManager, project, projectContext);

                // install the package
                foreach (PackageIdentity package in packages)
                {
                    if (package.Version == null)
                    {
                        if (!_packageServices.IsPackageInstalled(project, package.Id))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package.Id, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                    else
                    {
                        if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToString()))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
Exemplo n.º 14
0
 public static VsHierarchyItem FromDteProject(EnvDTE.Project project)
 {
     Assumes.Present(project);
     return(new VsHierarchyItem(VsHierarchyUtility.ToVsHierarchy(project)));
 }