public bool TryCreateNuGetProject(EnvDTE.Project dteProject, ProjectSystemProviderContext context, out NuGetProject result)
        {
            if (dteProject == null)
            {
                throw new ArgumentNullException(nameof(dteProject));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            result = null;

            var projectK = GetProjectKProject(dteProject);

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

            result = new ProjectKNuGetProject(
                projectK,
                dteProject.Name,
                EnvDTEProjectInfoUtility.GetCustomUniqueName(dteProject),
                VsHierarchyUtility.GetProjectId(dteProject));

            return(true);
        }
        public static string GetCustomUniqueName(PSObject psObject)
        {
            return(NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                return EnvDTEProjectInfoUtility.GetCustomUniqueName((Project)psObject.BaseObject);
            }));
        }
        public bool TryCreateNuGetProject(EnvDTE.Project dteProject, ProjectSystemProviderContext context, out NuGetProject result)
        {
            if (dteProject == null)
            {
                throw new ArgumentNullException(nameof(dteProject));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            result = null;

            // The project must be an IVsHierarchy.
            var hierarchy = VsHierarchyUtility.ToVsHierarchy(dteProject);

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

            // Check if the project is not CPS capable or if it is CPS capable then it does not have TargetFramework(s), if so then return false
            if (!hierarchy.IsCapabilityMatch("CPS"))
            {
                return(false);
            }

            var buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

            // read MSBuild property RestoreProjectStyle, TargetFramework, and TargetFrameworks
            var restoreProjectStyle = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, RestoreProjectStyle);

            var targetFramework = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, TargetFramework);

            var targetFrameworks = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, TargetFrameworks);

            // check for RestoreProjectStyle property is set and if not set to PackageReference then return false
            if (!(string.IsNullOrEmpty(restoreProjectStyle) ||
                  restoreProjectStyle.Equals(ProjectStyle.PackageReference.ToString(), StringComparison.OrdinalIgnoreCase)))
            {
                return(false);
            }
            // check whether TargetFramework or TargetFrameworks property is set, else return false
            else if (string.IsNullOrEmpty(targetFramework) && string.IsNullOrEmpty(targetFrameworks))
            {
                return(false);
            }

            // Lazy load the CPS enabled JoinableTaskFactory for the UI.
            NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor);

            var projectNames        = ProjectNames.FromDTEProject(dteProject);
            var fullProjectPath     = EnvDTEProjectInfoUtility.GetFullProjectPath(dteProject);
            var unconfiguredProject = GetUnconfiguredProject(dteProject);

            result = new CpsPackageReferenceProject(
                dteProject.Name,
                EnvDTEProjectInfoUtility.GetCustomUniqueName(dteProject),
                fullProjectPath,
                _projectSystemCache,
                dteProject,
                unconfiguredProject,
                VsHierarchyUtility.GetProjectId(dteProject));

            return(true);
        }
Beispiel #4
0
        public bool TryCreateNuGetProject(EnvDTE.Project envDTEProject, ProjectSystemProviderContext context, out NuGetProject result)
        {
            if (envDTEProject == null)
            {
                throw new ArgumentNullException(nameof(envDTEProject));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            result = null;

            var msBuildNuGetProjectSystem = MSBuildNuGetProjectSystemFactory.CreateMSBuildNuGetProjectSystem(
                envDTEProject,
                context.ProjectContext);

            var isWebSite = msBuildNuGetProjectSystem is WebSiteProjectSystem;

            // Web sites cannot have project.json
            if (!isWebSite)
            {
                // Find the project file path
                var projectFilePath = EnvDTEProjectInfoUtility.GetFullProjectPath(envDTEProject);

                if (!string.IsNullOrEmpty(projectFilePath))
                {
                    var msbuildProjectFile         = new FileInfo(projectFilePath);
                    var projectNameFromMSBuildPath = Path.GetFileNameWithoutExtension(msbuildProjectFile.Name);

                    // Treat projects with project.json as build integrated projects
                    // Search for projectName.project.json first, then project.json
                    // If the name cannot be determined, search only for project.json
                    string projectJsonPath = null;
                    if (string.IsNullOrEmpty(projectNameFromMSBuildPath))
                    {
                        projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName,
                                                       ProjectJsonPathUtilities.ProjectConfigFileName);
                    }
                    else
                    {
                        projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(msbuildProjectFile.DirectoryName,
                                                                                        projectNameFromMSBuildPath);
                    }

                    if (File.Exists(projectJsonPath))
                    {
                        result = new ProjectJsonBuildIntegratedProjectSystem(
                            projectJsonPath,
                            msbuildProjectFile.FullName,
                            envDTEProject,
                            EnvDTEProjectInfoUtility.GetCustomUniqueName(envDTEProject));
                    }
                }
            }

            // Create a normal MSBuild project if no project.json was found
            if (result == null)
            {
                var folderNuGetProjectFullPath = context.PackagesPathFactory();

                // Project folder path is the packages config folder path
                var packagesConfigFolderPath = EnvDTEProjectInfoUtility.GetFullPath(envDTEProject);

                result = new VSMSBuildNuGetProject(
                    envDTEProject,
                    msBuildNuGetProjectSystem,
                    folderNuGetProjectFullPath,
                    packagesConfigFolderPath);
            }

            return(result != null);
        }
        /// <summary>
        /// Return all projects in the solution matching the provided names. Wildcards are supported.
        /// This method will automatically generate error records for non-wildcarded project names that
        /// are not found.
        /// </summary>
        /// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
        /// <returns>Projects matching the project name(s) provided.</returns>
        protected IEnumerable <Project> GetProjectsByName(string[] projectNames)
        {
            var allValidProjectNames = GetAllValidProjectNames().ToList();
            var allDteProjects       = EnvDTESolutionUtility.GetAllEnvDTEProjects(DTE);

            foreach (string projectName in projectNames)
            {
                // if ctrl+c hit, leave immediately
                if (Stopping)
                {
                    break;
                }

                // Treat every name as a wildcard; results in simpler code
                var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);

                var matches = from s in allValidProjectNames
                              where pattern.IsMatch(s)
                              select VsSolutionManager.GetNuGetProject(s);

                int count = 0;
                foreach (var project in matches)
                {
                    if (project != null)
                    {
                        count++;
                        string  name       = project.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName);
                        Project dteProject = allDteProjects
                                             .Where(p => StringComparer.OrdinalIgnoreCase.Equals(EnvDTEProjectInfoUtility.GetCustomUniqueName(p), name))
                                             .FirstOrDefault();
                        yield return(dteProject);
                    }
                }

                // We only emit non-terminating error record if a non-wildcarded name was not found.
                // This is consistent with built-in cmdlets that support wildcarded search.
                // A search with a wildcard that returns nothing should not be considered an error.
                if ((count == 0) &&
                    !WildcardPattern.ContainsWildcardCharacters(projectName))
                {
                    ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
                }
            }
        }
        /// <summary>
        /// Get default project in the type of EnvDTE.Project, to keep PowerShell scripts backward-compatbility.
        /// </summary>
        /// <returns></returns>
        protected Project GetDefaultProject()
        {
            string  customUniqueName  = string.Empty;
            Project defaultDTEProject = null;

            NuGetProject defaultNuGetProject = VsSolutionManager.DefaultNuGetProject;

            // Solution may be open without a project in it. Then defaultNuGetProject is null.
            if (defaultNuGetProject != null)
            {
                customUniqueName = defaultNuGetProject.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName);
            }

            // Get all DTE projects in the solution and compare by CustomUnique names, especially for projects under solution folders.
            IEnumerable <Project> allDTEProjects = EnvDTESolutionUtility.GetAllEnvDTEProjects(DTE);

            if (allDTEProjects != null)
            {
                defaultDTEProject = allDTEProjects.Where(p => StringComparer.OrdinalIgnoreCase.Equals(EnvDTEProjectInfoUtility.GetCustomUniqueName(p), customUniqueName)).FirstOrDefault();
            }

            return(defaultDTEProject);
        }
        private async Task <IVsWindowFrame> CreateDocWindowAsync(
            Project project,
            string documentName,
            IVsHierarchy hier,
            uint itemId)
        {
            uint windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            if (!SolutionManager.IsSolutionAvailable)
            {
                throw new InvalidOperationException(Resources.SolutionIsNotSaved);
            }

            var nugetProject = SolutionManager.GetNuGetProject(EnvDTEProjectInfoUtility.GetCustomUniqueName(project));

            // If we failed to generate a cache entry in the solution manager something went wrong.
            if (nugetProject == null)
            {
                throw new InvalidOperationException(
                          string.Format(Resources.ProjectHasAnInvalidNuGetConfiguration, project.Name));
            }

            // load packages.config. This makes sure that an exception will get thrown if there
            // are problems with packages.config, such as duplicate packages. When an exception
            // is thrown, an error dialog will pop up and this doc window will not be created.
            var installedPackages = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

            var uiController = UIFactory.Create(nugetProject);

            var model = new PackageManagerModel(
                uiController,
                isSolution: false,
                editorFactoryGuid: GuidList.guidNuGetEditorType);

            var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory;

            var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4;

            var control        = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger);
            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = String.Format(
                CultureInfo.CurrentCulture,
                Resx.Label_NuGetWindowCaption,
                project.Name);

            IVsWindowFrame windowFrame;
            var            uiShell = await GetServiceAsync(typeof(SVsUIShell)) as IVsUIShell;

            IntPtr ppunkDocView = IntPtr.Zero;
            IntPtr ppunkDocData = IntPtr.Zero;
            int    hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)hier,
                    itemId,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }