Exemplo n.º 1
0
        public async Task <NuGetProject> UpdateNuGetProjectToPackageRef(NuGetProject oldProject)
        {
#if VS14
            // do nothing for VS 2015 and simply return the existing NuGetProject
            if (NuGetProjectUpdated != null)
            {
                NuGetProjectUpdated(this, new NuGetProjectEventArgs(oldProject));
            }

            return(await Task.FromResult(oldProject));
#else
            if (oldProject == null)
            {
                throw new ArgumentException(
                          ProjectManagement.Strings.Argument_Cannot_Be_Null_Or_Empty,
                          nameof(oldProject));
            }

            var projectName = GetNuGetProjectSafeName(oldProject);
            var dteProject  = GetDTEProject(projectName);

            ProjectNames oldEnvDTEProjectName;
            _projectSystemCache.TryGetProjectNames(projectName, out oldEnvDTEProjectName);

            RemoveEnvDTEProjectFromCache(projectName);

            var nuGetProject = await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var settings = ServiceLocator.GetInstance <ISettings>();

                var context = new ProjectSystemProviderContext(
                    EmptyNuGetProjectContext,
                    () => PackagesFolderPathUtility.GetPackagesFolderPath(this, settings));

                return(new LegacyCSProjPackageReferenceProject(
                           new EnvDTEProjectAdapter(dteProject),
                           VsHierarchyUtility.GetProjectId(dteProject)));
            });

            var added = _projectSystemCache.AddProject(oldEnvDTEProjectName, dteProject, nuGetProject);

            if (NuGetProjectUpdated != null)
            {
                NuGetProjectUpdated(this, new NuGetProjectEventArgs(nuGetProject));
            }

            return(nuGetProject);
#endif
        }
Exemplo n.º 2
0
        public static string GetSKU()
        {
            DTE    dte = ServiceLocator.GetInstance <DTE>();
            string sku = dte.Edition;

            if (sku.Equals("Ultimate", StringComparison.OrdinalIgnoreCase) ||
                sku.Equals("Premium", StringComparison.OrdinalIgnoreCase) ||
                sku.Equals("Professional", StringComparison.OrdinalIgnoreCase))
            {
                sku = "Pro";
            }

            return(sku);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out of date.
        /// The value does not matter, it just needs to change.
        /// </summary>
        protected static void UpdateImportStamp(EnvDTEProject envDTEProject, bool isCpsProjectSystem = false)
        {
            // There is no reason to call this for pre-Dev12 project systems.
            if (VSVersionHelper.VsMajorVersion >= 12)
            {
#if VS14
                // Switch to UI thread to update Import Stamp for Dev14.
                if (isCpsProjectSystem && VSVersionHelper.IsVisualStudio2014)
                {
                    try
                    {
                        var             projectServiceAccessor = ServiceLocator.GetInstance <IProjectServiceAccessor>();
                        ProjectService  projectService         = projectServiceAccessor.GetProjectService();
                        IThreadHandling threadHandling         = projectService.Services.ThreadingPolicy;
                        threadHandling.SwitchToUIThread();
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.WriteToActivityLog(ex);
                    }
                }
#endif

                IVsBuildPropertyStorage propStore = VsHierarchyUtility.ToVsHierarchy(envDTEProject) as IVsBuildPropertyStorage;
                if (propStore != null)
                {
                    // <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
                    string stamp = Guid.NewGuid().ToString().Split('-')[0];
                    try
                    {
                        int r1 = propStore.SetPropertyValue(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp);
                    }
                    catch (Exception ex1)
                    {
                        ExceptionHelper.WriteToActivityLog(ex1);
                    }

                    // Remove the NuGetImportStamp so that VC++ project file won't be updated with this stamp on disk,
                    // which causes unnecessary source control pending changes.
                    try
                    {
                        int r2 = propStore.RemoveProperty(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE);
                    }
                    catch (Exception ex2)
                    {
                        ExceptionHelper.WriteToActivityLog(ex2);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public static IVsHierarchy ToVsHierarchy(Project project)
        {
            IVsHierarchy hierarchy;

            // Get the vs solution
            IVsSolution solution = ServiceLocator.GetInstance <IVsSolution>();
            int         hr       = solution.GetProjectOfUniqueName(EnvDTEProjectUtility.GetUniqueName(project), out hierarchy);

            if (hr != NuGetVSConstants.S_OK)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            return(hierarchy);
        }
Exemplo n.º 5
0
        public VSSolutionManager()
        {
            _dte                = ServiceLocator.GetInstance <DTE>();
            _vsSolution         = ServiceLocator.GetGlobalService <SVsSolution, IVsSolution>();
            _vsMonitorSelection = ServiceLocator.GetGlobalService <SVsShellMonitorSelection, IVsMonitorSelection>();

            // Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
            _solutionEvents = _dte.Events.SolutionEvents;

            // can be null in unit tests
            if (_vsMonitorSelection != null)
            {
                Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
                _vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);

                uint cookie;
                int  hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie);
                ErrorHandler.ThrowOnFailure(hr);
            }

            // Allow this constructor to be invoked from either the UI or a worker thread. This JTF call should be
            // cheap (minimal context switch cost) when we are already on the UI thread.
            ThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                UserAgent.SetUserAgentString(
                    new UserAgentStringBuilder().WithVisualStudioSKU(VSVersionHelper.GetFullVsVersionString()));
            });

            _solutionEvents.BeforeClosing  += OnBeforeClosing;
            _solutionEvents.AfterClosing   += OnAfterClosing;
            _solutionEvents.ProjectAdded   += OnEnvDTEProjectAdded;
            _solutionEvents.ProjectRemoved += OnEnvDTEProjectRemoved;
            _solutionEvents.ProjectRenamed += OnEnvDTEProjectRenamed;

            var vSStd97CmdIDGUID = VSConstants.GUID_VSStandardCommandSet97.ToString("B");
            var solutionSaveID   = (int)VSConstants.VSStd97CmdID.SaveSolution;
            var solutionSaveAsID = (int)VSConstants.VSStd97CmdID.SaveSolutionAs;

            _solutionSaveEvent   = _dte.Events.CommandEvents[vSStd97CmdIDGUID, solutionSaveID];
            _solutionSaveAsEvent = _dte.Events.CommandEvents[vSStd97CmdIDGUID, solutionSaveAsID];

            _solutionSaveEvent.BeforeExecute   += SolutionSaveAs_BeforeExecute;
            _solutionSaveEvent.AfterExecute    += SolutionSaveAs_AfterExecute;
            _solutionSaveAsEvent.BeforeExecute += SolutionSaveAs_BeforeExecute;
            _solutionSaveAsEvent.AfterExecute  += SolutionSaveAs_AfterExecute;
        }
        public static bool?ShowQueryMessage(string message, string title, bool showCancelButton)
        {
            int result = VsShellUtilities.ShowMessageBox(
                ServiceLocator.GetInstance <IServiceProvider>(),
                message,
                title,
                OLEMSGICON.OLEMSGICON_QUERY,
                showCancelButton ? OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL : OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            if (result == NativeMethods.IDCANCEL)
            {
                return(null);
            }
            return(result == NativeMethods.IDYES);
        }
Exemplo n.º 7
0
        private NuGetProject CreateNuGetProject(Project envDTEProject, INuGetProjectContext projectContext = null)
        {
            var settings = ServiceLocator.GetInstance <ISettings>();

            var context = new ProjectSystemProviderContext(
                projectContext ?? EmptyNuGetProjectContext,
                () => PackagesFolderPathUtility.GetPackagesFolderPath(this, settings));

            NuGetProject result;

            if (_projectSystemFactory.TryCreateNuGetProject(envDTEProject, context, out result))
            {
                return(result);
            }

            return(null);
        }
        public static string GetFullVsVersionString()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            DTE dte = ServiceLocator.GetInstance <DTE>();

            // On Dev14, dte.Edition just returns SKU, such as "Enterprise"
            // Add "VS" to the string so that in user agent header, it will be "VS Enterprise/14.0".
            string edition = dte.Edition;

            if (!edition.StartsWith("VS", StringComparison.OrdinalIgnoreCase))
            {
                edition = "VS " + edition;
            }

            return(edition + "/" + dte.Version);
        }
Exemplo n.º 9
0
        public static async Task CollapseAllNodesAsync(ISolutionManager solutionManager, IDictionary <string, ISet <VsHierarchyItem> > ignoreNodes)
        {
            // this operation needs to execute on UI thread
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var dte      = ServiceLocator.GetInstance <DTE>();
            var projects = dte.Solution.Projects;

            foreach (Project project in projects)
            {
                ISet <VsHierarchyItem> expandedNodes;
                if (ignoreNodes.TryGetValue(EnvDTEProjectUtility.GetUniqueName(project), out expandedNodes)
                    &&
                    expandedNodes != null)
                {
                    CollapseProjectHierarchyItems(project, expandedNodes);
                }
            }
        }
Exemplo n.º 10
0
        public static async TaskExpandedNodes GetAllExpandedNodesAsync(ISolutionManager solutionManager)
        {
            // this operation needs to execute on UI thread
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var dte      = ServiceLocator.GetInstance <DTE>();
            var projects = dte.Solution.Projects;

            var results = new Dictionary <string, ISet <VsHierarchyItem> >(StringComparer.OrdinalIgnoreCase);

            foreach (Project project in projects)
            {
                ICollection <VsHierarchyItem> expandedNodes =
                    GetExpandedProjectHierarchyItems(project);
                Debug.Assert(!results.ContainsKey(EnvDTEProjectUtility.GetUniqueName(project)));
                results[EnvDTEProjectUtility.GetUniqueName(project)] =
                    new HashSet <VsHierarchyItem>(expandedNodes);
            }
            return(results);
        }
Exemplo n.º 11
0
        public VSSolutionManager()
        {
            _dte                = ServiceLocator.GetInstance <DTE>();
            _vsSolution         = ServiceLocator.GetGlobalService <SVsSolution, IVsSolution>();
            _vsMonitorSelection = ServiceLocator.GetGlobalService <SVsShellMonitorSelection, IVsMonitorSelection>();

            // Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
            _solutionEvents = _dte.Events.SolutionEvents;

            // can be null in unit tests
            if (_vsMonitorSelection != null)
            {
                Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
                _vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);

                uint cookie;
                int  hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie);
                ErrorHandler.ThrowOnFailure(hr);
            }

            UserAgent.SetUserAgentString(
                new UserAgentStringBuilder().WithVisualStudioSKU(VSVersionHelper.GetFullVsVersionString()));

            _solutionEvents.BeforeClosing  += OnBeforeClosing;
            _solutionEvents.AfterClosing   += OnAfterClosing;
            _solutionEvents.ProjectAdded   += OnEnvDTEProjectAdded;
            _solutionEvents.ProjectRemoved += OnEnvDTEProjectRemoved;
            _solutionEvents.ProjectRenamed += OnEnvDTEProjectRenamed;

            var vSStd97CmdIDGUID = VSConstants.GUID_VSStandardCommandSet97.ToString("B");
            var solutionSaveID   = (int)VSConstants.VSStd97CmdID.SaveSolution;
            var solutionSaveAsID = (int)VSConstants.VSStd97CmdID.SaveSolutionAs;

            _solutionSaveEvent   = _dte.Events.CommandEvents[vSStd97CmdIDGUID, solutionSaveID];
            _solutionSaveAsEvent = _dte.Events.CommandEvents[vSStd97CmdIDGUID, solutionSaveAsID];

            _solutionSaveEvent.BeforeExecute   += SolutionSaveAs_BeforeExecute;
            _solutionSaveEvent.AfterExecute    += SolutionSaveAs_AfterExecute;
            _solutionSaveAsEvent.BeforeExecute += SolutionSaveAs_BeforeExecute;
            _solutionSaveAsEvent.AfterExecute  += SolutionSaveAs_AfterExecute;
        }
Exemplo n.º 12
0
        public static IVsProjectBuildSystem GetVsProjectBuildSystem(EnvDTE.Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            return(NuGetUIThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                // Get the vs solution
                IVsSolution solution = ServiceLocator.GetInstance <IVsSolution>();
                IVsHierarchy hierarchy;
                var hr = solution.GetProjectOfUniqueName(EnvDTEProjectInfoUtility.GetUniqueName(project), out hierarchy);

                if (hr != VSConstants.S_OK)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                return hierarchy as IVsProjectBuildSystem;
            }));
        }
Exemplo n.º 13
0
        public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync(
            Common.ILogger logger, CancellationToken _)
        {
            // DTE calls need to be done from the main thread
            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var results = new List <ProjectRestoreReference>();

            var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>();

            // Verify ReferenceOutputAssembly
            var excludedProjects     = GetExcludedReferences(itemsFactory, logger);
            var hasMissingReferences = false;

            // find all references in the project
            foreach (var childReference in GetVSProjectReferences())
            {
                try
                {
                    var reference3 = childReference as Reference3;

                    // Verify that this is a project reference
                    if (IsProjectReference(reference3, logger))
                    {
                        // Verify that this is a valid and resolved project reference
                        if (!IsReferenceResolved(reference3, logger))
                        {
                            hasMissingReferences = true;
                            continue;
                        }

                        if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(reference3.SourceProject))
                        {
                            // Skip this shared project
                            continue;
                        }

                        var childProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(reference3.SourceProject);

                        // Skip projects which have ReferenceOutputAssembly=false
                        if (!string.IsNullOrEmpty(childProjectPath) &&
                            !excludedProjects.Contains(childProjectPath, StringComparer.OrdinalIgnoreCase))
                        {
                            var restoreReference = new ProjectRestoreReference()
                            {
                                ProjectPath       = childProjectPath,
                                ProjectUniqueName = childProjectPath
                            };

                            results.Add(restoreReference);
                        }
                    }
                    else
                    {
                        hasMissingReferences = true;
                    }
                }
                catch (Exception ex)
                {
                    // Exceptions are expected in some scenarios for native projects,
                    // ignore them and show a warning
                    hasMissingReferences = true;

                    logger.LogDebug(ex.ToString());

                    Debug.Fail("Unable to find project dependencies: " + ex.ToString());
                }
            }

            if (hasMissingReferences)
            {
                // Log a generic message once per project if any items could not be resolved.
                // In most cases this can be ignored, but in the rare case where the unresolved
                // item is actually a project the restore result will be incomplete.
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.UnresolvedItemDuringProjectClosureWalk,
                    _vsProjectAdapter.UniqueName);

                logger.LogVerbose(message);
            }

            return(results);
        }
Exemplo n.º 14
0
 public VsMachineWideSettings()
     : this(ServiceLocator.GetInstance <DTE>())
 {
 }
 /// <summary>
 /// Creates a new instance of <see cref="VsDeleteOnRestartManager"/>.
 /// </summary>
 public VsDeleteOnRestartManager() : this(
     ServiceLocator.GetInstance<Configuration.ISettings>(),
     ServiceLocator.GetInstance<ISolutionManager>())
 {
 }
        /// <summary>
        /// Returns the closure of all project to project references below this project.
        /// </summary>
        /// <remarks>This uses DTE and should be called from the UI thread.</remarks>
        public override async Task <IReadOnlyList <ExternalProjectReference> > GetProjectReferenceClosureAsync(
            ExternalProjectReferenceContext context)
        {
            var logger = context.Logger;
            var cache  = context.Cache;

            // DTE calls need to be done from the main thread
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var results = new HashSet <ExternalProjectReference>();

            // projects to walk - DFS
            var toProcess = new Stack <DTEReference>();

            // keep track of found projects to avoid duplicates
            var rootProjectPath = EnvDTEProjectUtility.GetFullProjectPath(EnvDTEProject);

            // start with the current project
            toProcess.Push(new DTEReference(EnvDTEProject, rootProjectPath));

            var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>();
            var uniqueNames  = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            // continue walking all project references until we run out
            while (toProcess.Count > 0)
            {
                var dteReference = toProcess.Pop();

                // Find the path of the current project
                var projectFileFullPath = dteReference.Path;
                var project             = dteReference.Project;

                if (string.IsNullOrEmpty(projectFileFullPath) || !uniqueNames.Add(projectFileFullPath))
                {
                    // This has already been processed or does not exist
                    continue;
                }

                IReadOnlyList <ExternalProjectReference> cacheReferences;
                if (cache.TryGetValue(projectFileFullPath, out cacheReferences))
                {
                    // The cached value contains the entire closure, add it to the results and skip
                    // all child references.
                    results.UnionWith(cacheReferences);
                }
                else
                {
                    // Get direct references
                    var projectResult = GetDirectProjectReferences(
                        dteReference.Project,
                        projectFileFullPath,
                        context,
                        itemsFactory,
                        rootProjectPath);

                    // Add results to the closure
                    results.UnionWith(projectResult.Processed);

                    // Continue processing
                    foreach (var item in projectResult.ToProcess)
                    {
                        toProcess.Push(item);
                    }
                }
            }

            // Cache the results for this project and every child project which has not been cached
            foreach (var project in results)
            {
                if (!context.Cache.ContainsKey(project.UniqueName))
                {
                    var closure = BuildIntegratedRestoreUtility.GetExternalClosure(project.UniqueName, results);

                    context.Cache.Add(project.UniqueName, closure.ToList());
                }
            }

            return(cache[rootProjectPath]);
        }
Exemplo n.º 17
0
 public VsCommonOperations()
     : this(ServiceLocator.GetInstance <DTE>())
 {
 }
Exemplo n.º 18
0
 /// <summary>
 /// Gets the VsSettings singleton object.
 /// </summary>
 /// <returns>The VsSettings object in the system.</returns>
 public static Configuration.ISettings GetVsSettings()
 {
     return(ServiceLocator.GetInstance <Configuration.ISettings>());
 }
        private async Task <(IPackageFeed?mainFeed, IPackageFeed?recommenderFeed)> CreatePackageFeedAsync(
            IReadOnlyCollection <IProjectContextInfo> projectContextInfos,
            IReadOnlyCollection <string> targetFrameworks,
            ItemFilter itemFilter,
            bool recommendPackages,
            IEnumerable <SourceRepository> sourceRepositories,
            CancellationToken cancellationToken)
        {
            var logger       = new VisualStudioActivityLogger();
            var uiLogger     = ServiceLocator.GetInstance <INuGetUILogger>();
            var packageFeeds = (mainFeed: (IPackageFeed?)null, recommenderFeed: (IPackageFeed?)null);

            if (itemFilter == ItemFilter.All && recommendPackages == false)
            {
                packageFeeds.mainFeed = new MultiSourcePackageFeed(sourceRepositories, uiLogger, TelemetryActivity.NuGetTelemetryService);
                return(packageFeeds);
            }

            IInstalledAndTransitivePackages installedAndTransitivePackages = await GetInstalledAndTransitivePackagesAsync(projectContextInfos, cancellationToken);

            PackageCollection installedPackageCollection  = PackageCollection.FromPackageReferences(installedAndTransitivePackages.InstalledPackages);
            PackageCollection transitivePackageCollection = PackageCollection.FromPackageReferences(installedAndTransitivePackages.TransitivePackages);

            SourceRepository packagesFolderSourceRepository = await _packagesFolderLocalRepositoryLazy.GetValueAsync(cancellationToken);

            IEnumerable <SourceRepository> globalPackageFolderRepositories = await _globalPackageFolderRepositoriesLazy.GetValueAsync(cancellationToken);

            var metadataProvider = new MultiSourcePackageMetadataProvider(
                sourceRepositories,
                packagesFolderSourceRepository,
                globalPackageFolderRepositories,
                logger);

            if (itemFilter == ItemFilter.All)
            {
                // if we get here, recommendPackages == true
                packageFeeds.mainFeed        = new MultiSourcePackageFeed(sourceRepositories, uiLogger, TelemetryActivity.NuGetTelemetryService);
                packageFeeds.recommenderFeed = new RecommenderPackageFeed(
                    sourceRepositories,
                    installedPackageCollection,
                    transitivePackageCollection,
                    targetFrameworks,
                    metadataProvider,
                    logger);
                return(packageFeeds);
            }

            if (itemFilter == ItemFilter.Installed)
            {
                packageFeeds.mainFeed = new InstalledPackageFeed(installedPackageCollection, metadataProvider, logger);
                return(packageFeeds);
            }

            if (itemFilter == ItemFilter.Consolidate)
            {
                packageFeeds.mainFeed = new ConsolidatePackageFeed(installedPackageCollection, metadataProvider, logger);
                return(packageFeeds);
            }

            // Search all / updates available cannot work without a source repo
            if (sourceRepositories == null)
            {
                return(packageFeeds);
            }

            if (itemFilter == ItemFilter.UpdatesAvailable)
            {
                packageFeeds.mainFeed = new UpdatePackageFeed(
                    _serviceBroker,
                    installedPackageCollection,
                    metadataProvider,
                    projectContextInfos.ToArray());

                return(packageFeeds);
            }

            throw new InvalidOperationException(
                      string.Format(CultureInfo.CurrentCulture, Strings.UnsupportedFeedType, itemFilter));
        }
        /// <summary>
        /// Get only the direct dependencies from a project
        /// </summary>
        public static async Task <IReadOnlyList <ProjectRestoreReference> > GetDirectProjectReferences(
            EnvDTEProject project,
            IEnumerable <string> resolvedProjects,
            ILogger log)
        {
            return(await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                // DTE calls need to be done from the main thread
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var results = new List <ProjectRestoreReference>();

                var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>();

                // Verify ReferenceOutputAssembly
                var excludedProjects = GetExcludedReferences(project, itemsFactory);
                var hasMissingReferences = false;

                // find all references in the project
                foreach (var childReference in GetProjectReferences(project))
                {
                    try
                    {
                        var reference3 = childReference as Reference3;

                        // check if deferred projects resolved this reference, which means this is still not loaded so simply continue
                        // We'll get this reference from deferred projects later
                        if (reference3 != null &&
                            resolvedProjects.Contains(reference3.Name, StringComparer.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        // Set missing reference if
                        // 1. reference is null OR
                        // 2. reference is not resolved which means project is not loaded or assembly not found.
                        else if (reference3 == null || !reference3.Resolved)
                        {
                            // Skip missing references and show a warning
                            hasMissingReferences = true;
                            continue;
                        }

                        // Skip missing references
                        if (childReference.SourceProject != null)
                        {
                            if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(childReference.SourceProject))
                            {
                                // Skip this shared project
                                continue;
                            }

                            var childProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(childReference.SourceProject);

                            // Skip projects which have ReferenceOutputAssembly=false
                            if (!string.IsNullOrEmpty(childProjectPath) &&
                                !excludedProjects.Contains(childProjectPath, StringComparer.OrdinalIgnoreCase))
                            {
                                var restoreReference = new ProjectRestoreReference()
                                {
                                    ProjectPath = childProjectPath,
                                    ProjectUniqueName = childProjectPath
                                };

                                results.Add(restoreReference);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Exceptions are expected in some scenarios for native projects,
                        // ignore them and show a warning
                        hasMissingReferences = true;

                        log.LogDebug(ex.ToString());

                        Debug.Fail("Unable to find project dependencies: " + ex.ToString());
                    }
                }

                if (hasMissingReferences)
                {
                    // Log a generic message once per project if any items could not be resolved.
                    // In most cases this can be ignored, but in the rare case where the unresolved
                    // item is actually a project the restore result will be incomplete.
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.UnresolvedItemDuringProjectClosureWalk,
                        EnvDTEProjectInfoUtility.GetUniqueName(project));

                    log.LogVerbose(message);
                }

                return results;
            }));
        }
Exemplo n.º 21
0
 public VsProductUpdateSettings() :
     this(ServiceLocator.GetInstance <IServiceProvider>())
 {
 }
Exemplo n.º 22
0
        public static async Task <bool> IsNuGetProjectUpgradeableAsync(NuGetProject nuGetProject, Project envDTEProject = null)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (nuGetProject == null && envDTEProject == null)
            {
                return(false);
            }

            if (nuGetProject == null)
            {
                var solutionManager = ServiceLocator.GetInstance <IVsSolutionManager>();

                var projectSafeName = await EnvDTEProjectInfoUtility.GetCustomUniqueNameAsync(envDTEProject);

                nuGetProject = await solutionManager.GetNuGetProjectAsync(projectSafeName);

                if (nuGetProject == null)
                {
                    return(false);
                }
            }

            // check if current project is packages.config based or not
            var msBuildNuGetProject = nuGetProject as MSBuildNuGetProject;

            if (msBuildNuGetProject == null || !msBuildNuGetProject.PackagesConfigNuGetProject.PackagesConfigExists())
            {
                return(false);
            }

            // this further check if current project system supports VSProject4 or not which is essential to skip
            // projects like c++ which currently doesn't support VSProject4 implementation for PackageReference
            if (!msBuildNuGetProject.ProjectServices.Capabilities.SupportsPackageReferences)
            {
                return(false);
            }

            if (envDTEProject == null)
            {
                var vsmsBuildNuGetProjectSystem =
                    msBuildNuGetProject.ProjectSystem as VsMSBuildProjectSystem;
                if (vsmsBuildNuGetProjectSystem == null)
                {
                    return(false);
                }
                envDTEProject = vsmsBuildNuGetProjectSystem.VsProjectAdapter.Project;
            }

            if (!EnvDTEProjectUtility.IsSupported(envDTEProject))
            {
                return(false);
            }
            var projectGuids = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject);

            if (projectGuids.Any(t => UnupgradeableProjectTypes.Contains(t)))
            {
                return(false);
            }

            // Project is supported language, and not an unsupported type
            return(UpgradeableProjectTypes.Contains(envDTEProject.Kind) &&
                   projectGuids.All(projectTypeGuid => !SupportedProjectTypes.IsUnsupported(projectTypeGuid)));
        }
Exemplo n.º 23
0
 public VSSourceControlManagerProvider()
     : this(ServiceLocator.GetInstance <DTE>(),
            ServiceLocator.GetGlobalService <SComponentModel, IComponentModel>())
 {
 }
Exemplo n.º 24
0
 public InteractiveLoginProvider()
 {
     _dte = ServiceLocator.GetInstance <DTE>();
 }
Exemplo n.º 25
0
 /// <summary>
 /// Gets the VsSettings singleton object.
 /// </summary>
 /// <returns>The VsSettings object in the system.</returns>
 public static ISettings GetVsSettings()
 {
     return(ServiceLocator.GetInstance <ISettings>());
 }