public bool IsFileInProject(Project project, string file)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (string.IsNullOrWhiteSpace(file))
            {
                throw new ArgumentNullException(nameof(file));
            }

            IVsSolution solution = this.serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;

            Debug.Assert(solution != null, "Cannot find SVsSolution");

            IVsHierarchy projectHierarchy;

            if (ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy)))
            {
                IVsProject           vsProject = projectHierarchy as IVsProject;
                int                  pfFound;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
                uint                 itemId;
                if (ErrorHandler.Succeeded(vsProject.IsDocumentInProject(file, out pfFound, pdwPriority, out itemId)) && pfFound != 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #2
0
        private void IsDocumentInAnotherProject(string originalPath, out IVsHierarchy hierOpen, out uint itemId, out int isDocInProj)
        {
            var vsSolution            = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            var rguidEnumOnlyThisType = Guid.Empty;
            IEnumHierarchies ppenum;

            itemId      = uint.MaxValue;
            hierOpen    = null;
            isDocInProj = 0;
            vsSolution.GetProjectEnum((int)__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, ref rguidEnumOnlyThisType, out ppenum);
            if (ppenum == null)
            {
                return;
            }

            ppenum.Reset();
            uint pceltFetched = 1U;
            var  rgelt        = new IVsHierarchy[1];

            ppenum.Next(1U, rgelt, out pceltFetched);
            while ((int)pceltFetched == 1)
            {
                var  vsProject   = rgelt[0] as IVsProject;
                var  pdwPriority = new VSDOCUMENTPRIORITY[1];
                uint pitemid;
                vsProject.IsDocumentInProject(originalPath, out isDocInProj, pdwPriority, out pitemid);
                if (isDocInProj == 1)
                {
                    hierOpen = rgelt[0];
                    itemId   = pitemid;
                    break;
                }
                ppenum.Next(1U, rgelt, out pceltFetched);
            }
        }
        /// <summary>
        ///     Returns the <see cref="HierarchyId"/> of the given document moniker, or
        ///     <see cref="HierarchyId.Nil"/> if the document moniker is not part of the project.
        /// </summary>
        public static HierarchyId GetHierarchyId(this IVsProject project, string documentMoniker)
        {
            Requires.NotNull(project, nameof(project));
            Requires.NotNullOrEmpty(documentMoniker, nameof(documentMoniker));

            var     priority = new VSDOCUMENTPRIORITY[1];
            int     isFound;
            uint    itemId;
            HResult result = project.IsDocumentInProject(documentMoniker, out isFound, priority, out itemId);

            if (result.Failed)
            {
                throw result.Exception;
            }

            // We only return items that are actually part of the project. CPS returns non-member from this API.
            if (isFound == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard && priority[0] != VSDOCUMENTPRIORITY.DP_Intrinsic)
            {
                return(HierarchyId.Nil);
            }

            HierarchyId id = itemId;

            Assumes.False(id.IsNilOrEmpty);

            return(id);
        }
Пример #4
0
        private int OpenItemViaMiscellaneousProject(uint flags, string moniker, ref Guid rguidLogicalView, out IVsWindowFrame ppWindowFrame)
        {
            ppWindowFrame = null;

            var miscellaneousProject = VsShellUtilities.GetMiscellaneousProject(this._serviceProvider);
            int hresult = VSConstants.E_FAIL;

            if (miscellaneousProject != null &&
                _serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) is IVsUIShellOpenDocument)
            {
                var externalFilesManager = this._serviceProvider.GetService(typeof(SVsExternalFilesManager)) as IVsExternalFilesManager;
                externalFilesManager.TransferDocument(null, moniker, null);
                IVsProject ppProject;
                hresult = externalFilesManager.GetExternalFilesProject(out ppProject);
                if (ppProject != null)
                {
                    int  pfFound;
                    uint pitemid;
                    var  pdwPriority = new VSDOCUMENTPRIORITY[1];
                    hresult = ppProject.IsDocumentInProject(moniker, out pfFound, pdwPriority, out pitemid);
                    if (pfFound == 1 && (int)pitemid != -1)
                    {
                        hresult = ppProject.OpenItem(pitemid, ref rguidLogicalView, IntPtr.Zero, out ppWindowFrame);
                    }
                }
            }
            return(hresult);
        }
Пример #5
0
        private ProjectItem GetProjectItem(string document, string codeBehind, string codeBehindFile)
        {
            // grabbed from Microsoft.VisualStudio.Web.Application.VsHierarchyItem.ctor(IVsHierarchy hier)
            IVsProject project = _hierarchy as IVsProject;

            if (project != null)
            {
                int  pfFound  = 0;
                uint vsitemid = uint.MaxValue;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                if (project.IsDocumentInProject(codeBehindFile, out pfFound, pdwPriority, out vsitemid) == NativeMethods.S_OK &&
                    (pfFound != 0) &&
                    (vsitemid != uint.MaxValue))
                {
                    var    propid = __VSHPROPID.VSHPROPID_ExtObject;
                    object pvar   = null;

                    _hierarchy.GetProperty(vsitemid, (int)propid, out pvar);

                    return(pvar as ProjectItem);
                }
            }

            return(null);
        }
        private async Task <(HierarchyId itemid, IVsHierarchy?hierarchy, IVsContainedLanguageFactory?containedLanguageFactory)> GetContainedLanguageFactoryForFileAsync(string filePath)
        {
            await _projectContextHost.PublishAsync();

            await _projectVsServices.ThreadingService.SwitchToUIThread();

            var     priority = new VSDOCUMENTPRIORITY[1];
            HResult result   = _projectVsServices.VsProject.IsDocumentInProject(filePath, out int isFound, priority, out uint itemid);

            if (result.Failed || isFound == 0)
            {
                return(HierarchyId.Nil, null, null);
            }

            Assumes.False(itemid == HierarchyId.Nil);

            IVsContainedLanguageFactory?containedLanguageFactory = await _containedLanguageFactory.GetValueAsync();

            if (containedLanguageFactory == null)
            {
                return(HierarchyId.Nil, null, null);
            }

            return(itemid, _projectVsServices.VsHierarchy, containedLanguageFactory);
        }
Пример #7
0
        private async Task <(HierarchyId itemid, IVsHierarchy hierarchy, IVsContainedLanguageFactory containedLanguageFactory)> GetContainedLanguageFactoryForFileAsync(string filePath)
        {
            await _languageServiceHost.InitializeAsync();

            await _projectVsServices.ThreadingService.SwitchToUIThread();

            var     priority = new VSDOCUMENTPRIORITY[1];
            HResult result   = _projectVsServices.VsProject.IsDocumentInProject(filePath, out int isFound, priority, out uint itemid);

            if (result.Failed || isFound == 0)
            {
                return(HierarchyId.Nil, null, null);
            }

            Assumes.False(itemid == HierarchyId.Nil);

            IVsContainedLanguageFactory containedLanguageFactory = await _containedLanguageFactory.GetValueAsync();

            if (containedLanguageFactory == null)
            {
                return(HierarchyId.Nil, null, null);
            }

            var hierarchy = (IVsHierarchy)_projectHostProvider.UnconfiguredProjectHostObject.ActiveIntellisenseProjectHostObject;

            if (hierarchy == null)
            {
                return(HierarchyId.Nil, null, null);
            }

            return(itemid, hierarchy, containedLanguageFactory);
        }
        public static void SetupGenerated(IVsProject project, EnvDTE.Configuration configuration, String filter, List <string> files, bool generatedFilesPerConfiguration)
        {
            List <string> missing = new List <string>();

            foreach (String file in files)
            {
                if (!Directory.Exists(Path.GetDirectoryName(file)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                }

                if (!File.Exists(file))
                {
                    File.Create(file).Dispose();
                }

                int  found;
                uint id;
                VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
                project.IsDocumentInProject(file, out found, priority, out id);
                if (found == 0)
                {
                    missing.Add(file);
                }
            }

            Package.Instance.VCUtil.AddGeneratedFiles(DTEUtil.GetProject(project as IVsHierarchy), configuration, filter, missing, generatedFilesPerConfiguration);
        }
Пример #9
0
        public static bool GetProjectAndFileInfoForPath(
            IVsProject vsProject, string originalPath, out IVsHierarchy projectHierarchy, out Project project, out uint fileItemId,
            out bool isDocInProject)
        {
            isDocInProject   = false;
            fileItemId       = 0;
            projectHierarchy = null;
            project          = null;

            var priority          = new VSDOCUMENTPRIORITY[1];
            var isDocInProjectInt = 0;

            uint foundItemId = 0;
            var  hr          = vsProject.IsDocumentInProject(originalPath, out isDocInProjectInt, priority, out foundItemId);

            if (NativeMethods.Succeeded(hr) && isDocInProjectInt == 1)
            {
                projectHierarchy = vsProject as IVsHierarchy;
                if (projectHierarchy != null)
                {
                    project = GetProject(projectHierarchy);
                }
                fileItemId     = foundItemId;
                isDocInProject = true;
            }
            return(isDocInProject);
        }
Пример #10
0
        public override void OnExecute(CommandEventArgs e)
        {
            SvnItem node = EnumTools.GetFirst(e.Selection.GetSelectedSvnItems(false));

            IAnkhCommandService cmd = e.GetService<IAnkhCommandService>();
            switch (e.Command)
            {
                case AnkhCommand.ItemSelectInRepositoryExplorer:
                    if (node == null || node.Uri == null)
                        return;

                    if (cmd != null)
                        cmd.DirectlyExecCommand(AnkhCommand.RepositoryBrowse, node.FullPath);
                    break;
                case AnkhCommand.ItemSelectInWorkingCopyExplorer:
                    if (node == null || !node.Exists)
                        return;

                    if (cmd != null)
                        cmd.DirectlyExecCommand(AnkhCommand.WorkingCopyBrowse, node.FullPath);
                    break;
                case AnkhCommand.ItemSelectInSolutionExplorer:
                    if (node == null)
                        return;

                    IVsUIHierarchyWindow hierWindow = VsShellUtilities.GetUIHierarchyWindow(e.Context, new Guid(ToolWindowGuids80.SolutionExplorer));

                    IVsProject project = VsShellUtilities.GetProject(e.Context, node.FullPath) as IVsProject;

                    if (hierWindow != null)
                    {
                        int found;
                        uint id;
                        VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                        if (project != null && ErrorHandler.Succeeded(project.IsDocumentInProject(node.FullPath, out found, prio, out id)) && found != 0)
                        {
                            hierWindow.ExpandItem(project as IVsUIHierarchy, id, EXPANDFLAGS.EXPF_SelectItem);
                        }
                        else if (string.Equals(node.FullPath, e.Selection.SolutionFilename, StringComparison.OrdinalIgnoreCase))
                            hierWindow.ExpandItem(e.GetService<IVsUIHierarchy>(typeof(SVsSolution)), VSConstants.VSITEMID_ROOT, EXPANDFLAGS.EXPF_SelectItem);

                        // Now try to activate the solution explorer
                        IVsWindowFrame solutionExplorer;
                        Guid solutionExplorerGuid = new Guid(ToolWindowGuids80.SolutionExplorer);
                        IVsUIShell shell = e.GetService<IVsUIShell>(typeof(SVsUIShell));

                        if (shell != null)
                        {
                            shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorerGuid, out solutionExplorer);

                            if (solutionExplorer != null)
                                solutionExplorer.Show();
                        }

                    }
                    break;
            }
        }
Пример #11
0
        /// <summary>
        /// Check whether the project contains a document.
        /// </summary>
        /// <param name="project">IVsProject</param>
        /// <param name="pszMkDocument">full path of document</param>
        /// <returns>true if project contains document</returns>
        public static uint IsDocumentInProject2(this IVsProject project, string pszMkDocument)
        {
            int  found;
            uint itemId;

            VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
            project.IsDocumentInProject(pszMkDocument, out found, prio, out itemId);
            return(found != 0 ? itemId : 0);
        }
Пример #12
0
        public static bool HasFile(this IVsProject project, string file)
        {
            var priority = new VSDOCUMENTPRIORITY[1];

            if (ErrorHandler.Succeeded(project.IsDocumentInProject(file, out int found, priority, out uint projectItemID)))
            {
                return(found != 0);
            }
            return(false);
        }
Пример #13
0
        private static ProjectItem RetrieveProjectItem(string documentPath)
        {
            int  itemFound;
            uint itemId;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

            DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;

            if (dte == null)
            {
                throw new InvalidOperationException("Cannot get the global service from package. DTE is null. Document path is " + documentPath);
            }

            Array ary = dte.ActiveSolutionProjects as Array;

            if (ary == null)
            {
                throw new InvalidOperationException("Cannot get the active solution projects. Document path is " + documentPath);
            }

            Project project = ary.GetValue(0) as Project;

            if (project == null)
            {
                throw new InvalidOperationException("Cannot get the first project. Document path is " + documentPath);
            }

            IVsProject vsProject = VsHelper.ToVsProject(project);

            if (project == null)
            {
                throw new InvalidOperationException("Cannot convert project to VS project. Document path is " + documentPath);
            }

            vsProject.IsDocumentInProject(documentPath, out itemFound, pdwPriority, out itemId);

            if (itemFound == 0 || itemId == 0)
            {
                throw new InvalidOperationException("VsProject.IsDocumentInProject failed to find the document in the project. Document path is " + documentPath);
            }

            IServiceProvider oleSp;

            vsProject.GetItemContext(itemId, out oleSp);
            if (oleSp == null)
            {
                throw new InvalidOperationException("Cannot get item context. Document path is " + documentPath);
            }

            ServiceProvider sp   = new ServiceProvider(oleSp);
            ProjectItem     item = sp.GetService(typeof(ProjectItem)) as ProjectItem;

            return(item);
        }
Пример #14
0
        private void CheckForItem(ProjectNode projectNode, ProjectItem item)
        {
            Assert.IsTrue(item != null, "No project item has been added from template to the modeling project");
            Assert.IsTrue(String.Compare(Path.GetExtension(item.Name), ".cs", StringComparison.OrdinalIgnoreCase) == 0, "The item has not been added as a moxl file!");

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemid;
            int  found;

            projectNode.IsDocumentInProject(item.get_FileNames(1), out found, priority, out itemid);
            Assert.IsTrue(found == 1, "The item " + item.Name + " has not been added to the project");
        }
        public void PerformRefresh(IEnumerable<SvnClientAction> sccRefreshItems)
        {
            Debug.Assert(RequiresForcedRefresh(), "Refreshing a project that manages itself");

            RefreshState state = new RefreshState(_context, ProjectHierarchy, VsProject, ProjectDirectory);

            if (state.VsProject == null || state.ProjectDirectory == null)
                return; // Can't fix it

            VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
            IVsHierarchy hierarchy = null;

            foreach (SvnClientAction action in sccRefreshItems)
            {
                if (!action.AddOrRemove)
                    continue; // Not for me

                SvnItem item = state.Cache[action.FullPath];
                if (!item.IsBelowPath(ProjectDirectory))
                    return;

                int found;
                uint id;

                // Check the real project here instead of our cache to keep the update initiative
                // at the project. Checking our cache might be unsafe, as we get file add and remove
                // events from the project while we are updating
                if (!ErrorHandler.Succeeded(VsProject.IsDocumentInProject(item.FullPath, out found, prio, out id)))
                    continue;

                bool bFound = (found != 0);

                if (!bFound)
                {
                    if (hierarchy == null)
                        hierarchy = VsProject as IVsHierarchy;

                    // We need this additional check to find directories in Websites
                    if (hierarchy != null &&
                        ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(item.FullPath, out id)))
                    {
                        bFound = (id != VSConstants.VSITEMID_NIL) && (id != VSConstants.VSITEMID_ROOT);
                    }
                }
                if (bFound == item.Exists)
                    continue; //

                if (!bFound)
                    state.AddItem(item);
                else
                    state.RemoveItem(item, id);
            }
        }
Пример #16
0
        /// <summary>
        ///     Gets an object that represents a host-specific IVsContainedLanguageFactory implementation and
        ///     IVsHierarchy and itemId specific to currently active target framework.
        /// </summary>
        /// <param name="filePath">Path to a file</param>
        /// <param name="hierarchy">Project hierarchy containing given file for current language service</param>
        /// <param name="itemid">item id of the given file</param>
        /// <param name="containedLanguageFactory">an instance of IVsContainedLanguageFactory specific for current language service</param>
        /// <returns></returns>
        public int GetContainedLanguageFactoryForFile(string filePath,
                                                      out IVsHierarchy hierarchy,
                                                      out uint itemid,
                                                      out IVsContainedLanguageFactory containedLanguageFactory)
        {
            uint         myItemId    = 0;
            IVsHierarchy myHierarchy = null;
            IVsContainedLanguageFactory myContainedLanguageFactory = null;

            _projectVsServices.ThreadingService.JoinableTaskFactory.Run(async() =>
            {
                await InitializeAsync().ConfigureAwait(false);

                Guid?languageServiceId = await GetLanguageServiceId().ConfigureAwait(false);
                if (languageServiceId == null)
                {
                    return;
                }

                await _projectVsServices.ThreadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

                var priority   = new VSDOCUMENTPRIORITY[1];
                HResult result = _projectVsServices.VsProject.IsDocumentInProject(filePath,
                                                                                  out int isFound,
                                                                                  priority,
                                                                                  out myItemId);
                if (result.Failed || isFound == 0)
                {
                    return;
                }

                myHierarchy = (IVsHierarchy)_projectHostProvider.UnconfiguredProjectHostObject.ActiveIntellisenseProjectHostObject;

                var oleServiceProvider = _serviceProvider.GetService(typeof(IOLEServiceProvider)) as IOLEServiceProvider;
                if (oleServiceProvider == null)
                {
                    return;
                }

                myContainedLanguageFactory = (IVsContainedLanguageFactory)PackageUtilities.QueryService(
                    oleServiceProvider,
                    languageServiceId.Value);
            });

            hierarchy = myHierarchy;
            itemid    = myItemId;
            containedLanguageFactory = myContainedLanguageFactory;

            return((myHierarchy == null || containedLanguageFactory == null)
                ? VSConstants.E_FAIL
                : VSConstants.S_OK);
        }
        /// <summary>
        /// Returns the VSItemId of the project item with the specified path in the given
        /// hierarchy, or VSITEMID.Nil if the file is not in the project
        /// </summary>
        private uint FindProjectItemId(IVsHierarchy vsHierarchy, string filePath)
        {
            var  vsProject = vsHierarchy as IVsProject;
            int  pfFound;
            uint itemId;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
            if (ErrorHandler.Succeeded(vsProject.IsDocumentInProject(filePath, out pfFound, pdwPriority, out itemId)) && pfFound != 0)
            {
                return(itemId);
            }
            return((uint)VSConstants.VSITEMID.Nil);
        }
        public static EnvDTE.ProjectItem GetProjectItem(this IVsProject project, string path)
        {
            int  found;
            uint item;
            var  priority = new VSDOCUMENTPRIORITY[1];

            ErrorHandler.ThrowOnFailure(project.IsDocumentInProject(path, out found, priority, out item));
            if (found == 0 || (priority[0] != VSDOCUMENTPRIORITY.DP_Standard && priority[0] != VSDOCUMENTPRIORITY.DP_Intrinsic))
            {
                return(null);
            }
            return(project.GetProjectItem(item));
        }
Пример #19
0
        public void AddGeneratedFile(IVsProject project, VCFilter filter, string path, EnvDTE.Configuration config)
        {
            int  found;
            uint id;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            project.IsDocumentInProject(path, out found, priority, out id);
            if (found == 0)
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                }

                VCFile file = null;
                if (config == null)
                {
                    file = filter.AddFile(path);
                }
                else
                {
                    filter = FindOrCreateFilter(filter, config.PlatformName);
                    filter = FindOrCreateFilter(filter, config.ConfigurationName);
                    file   = filter.AddFile(path);
                    foreach (VCFileConfiguration c in file.FileConfigurations)
                    {
                        if (!c.ProjectConfiguration.ConfigurationName.Equals(config.ConfigurationName) ||
                            !c.ProjectConfiguration.Platform.Name.Equals(config.PlatformName))
                        {
                            c.ExcludedFromBuild = true;
                        }
                    }
                }

                try
                {
                    //
                    // Remove the file otherwise it will be considered up to date.
                    //
                    File.Delete(path);
                }
                catch (Exception)
                {
                }
            }
        }
Пример #20
0
        public static async Task <bool> ContainsFileAsync(EnvDTE.Project envDTEProject, string path)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (string.Equals(envDTEProject.Kind, VsProjectTypes.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.FsharpProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.JsProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
            {
                // For Wix and Nemerle projects, IsDocumentInProject() returns not found
                // even though the file is in the project. So we use GetProjectItem()
                // instead. Nemerle is a high-level statically typed programming language for .NET platform
                // Note that pszMkDocument, the document moniker, passed to IsDocumentInProject(), must be a path to the file
                // for certain file-based project systems such as F#. And, not just a filename. For these project systems as well,
                // do the following
                var item = await GetProjectItemAsync(envDTEProject, path);

                return(item != null);
            }

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var hierarchy = await envDTEProject.ToVsHierarchyAsync();

            var vsProject = hierarchy as IVsProject;

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

            int pFound;

            if (VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy))
            {
                // REVIEW: We want to revisit this after RTM - the code in this if statement should be applied to every project type.
                // We're checking for VSDOCUMENTPRIORITY.DP_Standard here to see if the file is included in the project.
                // Original check (outside of if) did not have this.
                var priority = new VSDOCUMENTPRIORITY[1];
                var hr       = vsProject.IsDocumentInProject(path, out pFound, priority, out _);
                return(ErrorHandler.Succeeded(hr) && pFound == 1 && priority[0] >= VSDOCUMENTPRIORITY.DP_Standard);
            }

            var hres = vsProject.IsDocumentInProject(path, out pFound, Array.Empty <VSDOCUMENTPRIORITY>(), out _);

            return(ErrorHandler.Succeeded(hres) && pFound == 1);
        }
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var    sharedHier    = this.FindSharedProject();
            string sharedCaption = HierarchyUtilities.GetHierarchyProperty <string>(sharedHier, (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Caption);

            this.Output(string.Format("Found shared project: {0}\n", sharedCaption));

            var    activePlatformHier = this.GetActiveProjectContext(sharedHier);
            string activeCaption      = HierarchyUtilities.GetHierarchyProperty <string>(activePlatformHier, (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Caption);

            this.Output(string.Format("The active platform project: {0}\n", activeCaption));

            this.Output("Platform projects:\n");
            foreach (IVsHierarchy platformHier in this.EnumImportingProjects(sharedHier))
            {
                string platformCaption = HierarchyUtilities.GetHierarchyProperty <string>(platformHier, (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Caption);
                this.Output(string.Format(" * {0}\n", platformCaption));
            }

            this.Output("Walk the active platform project:\n");
            var sharedItemIds = new List <uint>();

            this.InspectHierarchyItems(activePlatformHier, (uint)VSConstants.VSITEMID.Root, 1, sharedItemIds);

            var    sharedItemId = sharedItemIds[0];
            string fullPath;

            ErrorHandler.ThrowOnFailure(((IVsProject)activePlatformHier).GetMkDocument(sharedItemId, out fullPath));
            this.Output(string.Format("Shared item full path: {0}\n", fullPath));

            var dte       = (EnvDTE.DTE) this.GetService(typeof(EnvDTE.DTE));
            var dteEvents = (EnvDTE80.Events2)dte.Events;

            dteEvents.ProjectItemsEvents.ItemRenamed += this.OnItemRenamed;
            HierarchyUtilities.TryGetHierarchyProperty(activePlatformHier, sharedItemId, (int)__VSHPROPID7.VSHPROPID_SharedProjectHierarchy, out sharedHier);

            uint itemIdInSharedHier;
            int  found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            if (ErrorHandler.Succeeded(((IVsProject)sharedHier).IsDocumentInProject(fullPath, out found, priority, out itemIdInSharedHier)) &&
                found != 0)
            {
                var newName = DateTime.Now.Ticks.ToString() + Path.GetExtension(fullPath);
                ErrorHandler.ThrowOnFailure(sharedHier.SetProperty(itemIdInSharedHier, (int)__VSHPROPID.VSHPROPID_EditLabel, newName));
                this.Output(string.Format("Renamed {0} to {1}\n", fullPath, newName));
            }

            dteEvents.ProjectItemsEvents.ItemRenamed -= this.OnItemRenamed;
        }
Пример #22
0
        private bool TryGetItemIdInSharedHierarchyInternal(IVsHierarchy hierarchy, uint itemId, IVsHierarchy sharedHierarchy, out uint itemIdInSharedHierarchy)
        {
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];

            if (ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out var fullPath)) &&
                ErrorHandler.Succeeded(((IVsProject)sharedHierarchy).IsDocumentInProject(fullPath, out var found, priority, out itemIdInSharedHierarchy)) &&
                found != 0 &&
                itemIdInSharedHierarchy != (uint)VSConstants.VSITEMID.Nil)
            {
                return(true);
            }

            itemIdInSharedHierarchy = (uint)VSConstants.VSITEMID.Nil;
            return(false);
        }
        /// <summary>
        ///     Gets an object that represents a host-specific IVsContainedLanguageFactory implementation.
        ///     Note: currently we have only one target framework and IVsHierarchy and itemId is returned as
        ///     they are from the unconfigured project. Later when combined intellisense is implemented, depending
        ///     on implementation we might need to have a logic that returns IVsHierarchy and itemId specific to
        ///     currently active target framework (thats how it was in Dev14's dnx/dotnet project system)
        /// </summary>
        /// <param name="filePath">Path to a file</param>
        /// <param name="hierarchy">Project hierarchy containing given file for current language service</param>
        /// <param name="itemid">item id of the given file</param>
        /// <param name="containedLanguageFactory">an instance of IVsContainedLanguageFactory specific for current language service</param>
        /// <returns></returns>
        public int GetContainedLanguageFactoryForFile(string filePath,
                                                      out IVsHierarchy hierarchy,
                                                      out uint itemid,
                                                      out IVsContainedLanguageFactory containedLanguageFactory)
        {
            uint         myItemId    = 0;
            IVsHierarchy myHierarchy = null;
            IVsContainedLanguageFactory myContainedLanguageFactory = null;

            ProjectServices.ThreadingService.JoinableTaskFactory.Run(async() =>
            {
                await ProjectServices.ThreadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

                var priority = new VSDOCUMENTPRIORITY[1];
                int isFound;
                HResult result = ProjectServices.VsProject.IsDocumentInProject(filePath,
                                                                               out isFound,
                                                                               priority,
                                                                               out myItemId);
                if (result.Failed || isFound == 0)
                {
                    return;
                }

                myHierarchy = ProjectServices.VsHierarchy;

                var oleServiceProvider = ServiceProvider.GetService(typeof(IOLEServiceProvider)) as IOLEServiceProvider;
                if (oleServiceProvider == null)
                {
                    return;
                }

                myContainedLanguageFactory = (IVsContainedLanguageFactory)PackageUtilities.QueryService(
                    oleServiceProvider,
                    LanguageServiceGuid);
            });

            hierarchy = myHierarchy;
            itemid    = myItemId;
            containedLanguageFactory = myContainedLanguageFactory;

            return((myHierarchy == null || containedLanguageFactory == null)
                ? VSConstants.E_FAIL
                : VSConstants.S_OK);
        }
Пример #24
0
        public string GetNameOfParentProject(Path path)
        {
            var actualPath = path.ActualPath;
            var prio = new VSDOCUMENTPRIORITY[1];
            foreach (var project in GetControllableProjects().OfType<IVsProject2>())
            {
                int pfFound;
                uint itemid;
                if ( ErrorHandler.Succeeded(project.IsDocumentInProject(actualPath, out pfFound, prio, out itemid)) && pfFound != 0 )
                {
                    object name;
                    ((IVsHierarchy)project).GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Name, out name);
                    return (string)name;
                }
            }

            return null;
        }
Пример #25
0
        /// <summary>
        /// This will add a file to the misc folders without actually opening the document in
        /// Visual Studio
        /// </summary>
        private void CreateHierarchy(string moniker, out IVsUIHierarchy vsUiHierarchy, out uint itemId)
        {
            vsUiHierarchy = null;
            itemId        = VSConstants.VSITEMID_NIL;

            var vsExternalFilesManager = _vsServiceProvider.GetService <SVsExternalFilesManager, IVsExternalFilesManager>();

            int            defaultPosition;
            IVsWindowFrame dummyWindowFrame;
            uint           flags = (uint)_VSRDTFLAGS.RDT_NonCreatable | (uint)_VSRDTFLAGS.RDT_PlaceHolderDoc;
            var            hr    = vsExternalFilesManager.AddDocument(
                dwCDW: flags,
                pszMkDocument: moniker,
                punkDocView: IntPtr.Zero,
                punkDocData: IntPtr.Zero,
                rguidEditorType: Guid.Empty,
                pszPhysicalView: null,
                rguidCmdUI: Guid.Empty,
                pszOwnerCaption: moniker,
                pszEditorCaption: null,
                pfDefaultPosition: out defaultPosition,
                ppWindowFrame: out dummyWindowFrame);

            ErrorHandler.ThrowOnFailure(hr);

            // Get the hierarchy for the document we added to the miscellaneous files project
            IVsProject vsProject;

            hr = vsExternalFilesManager.GetExternalFilesProject(out vsProject);
            ErrorHandler.ThrowOnFailure(hr);

            int found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            hr = vsProject.IsDocumentInProject(moniker, out found, priority, out itemId);
            ErrorHandler.ThrowOnFailure(hr);
            if (0 == found || VSConstants.VSITEMID_NIL == itemId)
            {
                throw new Exception("Could not find in project");
            }

            vsUiHierarchy = (IVsUIHierarchy)vsProject;
        }
Пример #26
0
        private ProjectItem _getTemplateProjectItem()
        {
            Project dteProject = _getTemplateProject();

            IVsProject vsProject = _dteProjectToVsProject(dteProject);

            int  iFound = 0;
            uint itemId = 0;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
            int result = vsProject.IsDocumentInProject(_host.TemplateFile, out iFound, pdwPriority, out itemId);

            if (result != VSConstants.S_OK)
            {
                throw new Exception("Unexpected error calling IVsProject.IsDocumentInProject");
            }
            if (iFound == 0)
            {
                throw new Exception("Cannot retrieve ProjectItem for template file");
            }
            if (itemId == 0)
            {
                throw new Exception("Cannot retrieve ProjectItem for template file");
            }

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider itemContext = null;
            result = vsProject.GetItemContext(itemId, out itemContext);
            if (result != VSConstants.S_OK)
            {
                throw new Exception("Unexpected error calling IVsProject.GetItemContext");
            }
            if (itemContext == null)
            {
                throw new Exception("IVsProject.GetItemContext returned null");
            }

            ServiceProvider itemContextService = new ServiceProvider(itemContext);
            ProjectItem     templateItem       = (ProjectItem)itemContextService.GetService(typeof(ProjectItem));

            Debug.Assert(templateItem != null, "itemContextService.GetService returned null");

            return(templateItem);
        }
        /// <inheritdoc/>
        int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
        {
            var idPathPair = this.idPathMap.Where(kvp => kvp.Value.Equals(pszMkDocument, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();

            if (idPathPair.Value != null)
            {
                pfFound     = Common.Constants.TRUE;
                pdwPriority = new VSDOCUMENTPRIORITY[] { VSDOCUMENTPRIORITY.DP_Standard };
                pitemid     = idPathPair.Key;
            }
            else
            {
                Trace.TraceInformation($"{this.GetType().Name}.{nameof(IVsProject.IsDocumentInProject)}: Document not found {pszMkDocument}");
                pfFound     = Common.Constants.FALSE;
                pdwPriority = new VSDOCUMENTPRIORITY[] { VSDOCUMENTPRIORITY.DP_Unsupported };
                pitemid     = 0;
            }

            return(VSConstants.S_OK);
        }
Пример #28
0
        public bool TryGetProjectFileId(string path, out uint itemId)
        {
            int  found;
            uint id;

            VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];

            if (!ExcludedFromScc &&
                VSErr.Succeeded(VsProject.IsDocumentInProject(path, out found, prio, out id)))
            {
                // Priority also returns information on whether the file can be added
                if (found != 0 && prio[0] >= VSDOCUMENTPRIORITY.DP_Standard && id != 0)
                {
                    itemId = id;
                    return(true);
                }
            }

            itemId = VSItemId.Nil;
            return(false);
        }
Пример #29
0
        /// <summary>
        /// Finds the item in the solution matching the specified file path.
        /// </summary>
        /// <param name="filePath">The absolute file path of a file that exists in the solution.</param>
        /// <returns><see langword="null"/> if the file wasn't found in the solution.</returns>
        public static async Task <PhysicalFile?> FromFileAsync(string filePath)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IEnumerable <IVsHierarchy> projects = await VS.Solutions.GetAllProjectHierarchiesAsync();

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];

            foreach (IVsHierarchy hierarchy in projects)
            {
                IVsProject proj = (IVsProject)hierarchy;
                proj.IsDocumentInProject(filePath, out int isFound, priority, out uint itemId);

                if (isFound == 1)
                {
                    return(await FromHierarchyAsync(hierarchy, itemId) as PhysicalFile);
                }
            }

            return(null);
        }
Пример #30
0
        //--------------------------------------------------------------------------------------------
        /// <summary>
        ///     Locates the item in the provided hierarchy using the provided moniker
        ///     and return a VsHierarchyItem for it
        /// </summary>
        //--------------------------------------------------------------------------------------------
        internal static VsHierarchyItem CreateFromMoniker(string moniker, IVsHierarchy hier)
        {
            VsHierarchyItem item = null;

            if (!string.IsNullOrEmpty(moniker) && hier != null)
            {
                IVsProject proj = hier as IVsProject;
                if (proj != null)
                {
                    int  hr;
                    int  isFound = 0;
                    uint itemid  = VSConstants.VSITEMID_NIL;
                    VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
                    hr = proj.IsDocumentInProject(moniker, out isFound, priority, out itemid);
                    if (ErrorHandler.Succeeded(hr) && isFound != 0 && itemid != VSConstants.VSITEMID_NIL)
                    {
                        item = new VsHierarchyItem(itemid, hier);
                    }
                }
            }

            return(item);
        }
Пример #31
0
        private void InvalidateParentItems(string[] oldFileNames, string[] newFileNames)
        {
            int pfFound;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
            uint        pItemid;
            List <uint> itemIds = new List <uint>();

            for (int i = 0; i < newFileNames.Length; i++)
            {
                if (Path.GetFileName(newFileNames[i]) == Path.GetFileName(oldFileNames[i]))
                {
                    continue;
                }
                ErrorHandler.ThrowOnFailure(innerProject.IsDocumentInProject(newFileNames[i], out pfFound, pdwPriority, out pItemid));
                if (pfFound == 0)
                {
                    continue;
                }
                itemIds.Add(pItemid);
            }
            InvalidateParentItems(itemIds);
        }
Пример #32
0
        internal static PythonProjectNode GetProject(this ITextBuffer buffer, IServiceProvider serviceProvider)
        {
            var path = buffer.GetFilePath();

            if (path != null)
            {
                var sln = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
                if (sln != null)
                {
                    foreach (var proj in sln.EnumerateLoadedPythonProjects())
                    {
                        int  found;
                        var  priority = new VSDOCUMENTPRIORITY[1];
                        uint itemId;
                        ErrorHandler.ThrowOnFailure(proj.IsDocumentInProject(path, out found, priority, out itemId));
                        if (found != 0)
                        {
                            return(proj);
                        }
                    }
                }
            }
            return(null);
        }
Пример #33
0
        private void OnAfterAddedGrammarHelperFile(IVsProject project, string currentFile)
        {
            int found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemId;

            if (ErrorHandler.Failed(project.IsDocumentInProject(currentFile, out found, priority, out itemId)))
            {
                return;
            }

            if (found == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard)
            {
                return;
            }

            IVsHierarchy            hierarchy            = project as IVsHierarchy;
            IVsBuildPropertyStorage buildPropertyStorage = project as IVsBuildPropertyStorage;

            if (hierarchy != null && buildPropertyStorage != null)
            {
                string dependentUpon;
                if (ErrorHandler.Failed(buildPropertyStorage.GetItemAttribute(itemId, "DependentUpon", out dependentUpon)))
                {
                    string[] stripExtensions = { ".cs", ".lexer", ".parser" };
                    string   parentFileName  = Path.GetFileName(currentFile);
                    while (!string.IsNullOrWhiteSpace(parentFileName) && Array.IndexOf(stripExtensions, Path.GetExtension(parentFileName).ToLowerInvariant()) >= 0)
                    {
                        parentFileName = Path.GetFileNameWithoutExtension(parentFileName);
                    }

                    int hr = buildPropertyStorage.SetItemAttribute(itemId, "DependentUpon", parentFileName);
                }
            }
        }
Пример #34
0
    public static bool GetProjectAndFileInfoForPath(
        IVsProject vsProject, string originalPath, out IVsHierarchy projectHierarchy, out Project project, out uint fileItemId,
        out bool isDocInProject) {
      isDocInProject = false;
      fileItemId = 0;
      projectHierarchy = null;
      project = null;

      var priority = new VSDOCUMENTPRIORITY[1];
      var isDocInProjectInt = 0;

      uint foundItemId = 0;
      var hr = vsProject.IsDocumentInProject(originalPath, out isDocInProjectInt, priority, out foundItemId);
      if (NativeMethods.Succeeded(hr) && isDocInProjectInt == 1) {
        projectHierarchy = vsProject as IVsHierarchy;
        if (projectHierarchy != null) {
          project = GetProject(projectHierarchy);
        }
        fileItemId = foundItemId;
        isDocInProject = true;
      }
      return isDocInProject;
    }
        private ProjectItem GetProjectItem(string document, string codeBehind, string codeBehindFile)
        {
            // grabbed from Microsoft.VisualStudio.Web.Application.VsHierarchyItem.ctor(IVsHierarchy hier)
            IVsProject project = _hierarchy as IVsProject;
            if (project != null)
            {
                int pfFound = 0;
                uint vsitemid = uint.MaxValue;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                if (project.IsDocumentInProject(codeBehindFile, out pfFound, pdwPriority, out vsitemid) == NativeMethods.S_OK &&
                    (pfFound != 0) &&
                    (vsitemid != uint.MaxValue))
                {
                    var propid = __VSHPROPID.VSHPROPID_ExtObject;
                    object pvar = null;

                    _hierarchy.GetProperty(vsitemid, (int)propid, out pvar);

                    return pvar as ProjectItem;
                }
            }

            return null;
        }
Пример #36
0
 private void InvalidateParentItems(string[] oldFileNames, string[] newFileNames)
 {
     int pfFound;
     VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
     uint pItemid;
     List<uint> itemIds = new List<uint>();
     for (int i = 0; i < newFileNames.Length; i++)
     {
         if (Path.GetFileName(newFileNames[i]) == Path.GetFileName(oldFileNames[i]))
             continue;
         ErrorHandler.ThrowOnFailure(innerProject.IsDocumentInProject(newFileNames[i], out pfFound, pdwPriority, out pItemid));
         if (pfFound == 0)
             continue;
         itemIds.Add(pItemid);
     }
     InvalidateParentItems(itemIds);
 }
Пример #37
0
        /// <summary>
        /// Implements IVsProject3::TransferItem
        /// This function is called when an open miscellaneous file is being transferred
        /// to our project. The sequence is for the shell to call AddItemWithSpecific and
        /// then use TransferItem to transfer the open document to our project.
        /// </summary>
        /// <param name="oldMkDoc">Old document name</param>
        /// <param name="newMkDoc">New document name</param>
        /// <param name="frame">Optional frame if the document is open</param>
        /// <returns></returns>
        public virtual int TransferItem(string oldMkDoc, string newMkDoc, IVsWindowFrame frame)
        {
            // Fail if hierarchy already closed
            if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
            {
                return VSConstants.E_FAIL;
            }
            //Fail if the document names passed are null.
            if (oldMkDoc == null || newMkDoc == null)
                return VSConstants.E_INVALIDARG;

            int hr = VSConstants.S_OK;
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemid = VSConstants.VSITEMID_NIL;
            uint cookie = 0;
            uint grfFlags = 0;

            IVsRunningDocumentTable pRdt = GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
            if (pRdt == null)
                return VSConstants.E_ABORT;

            string doc;
            int found;
            IVsHierarchy pHier;
            uint id, readLocks, editLocks;
            IntPtr docdataForCookiePtr = IntPtr.Zero;
            IntPtr docDataPtr = IntPtr.Zero;
            IntPtr hierPtr = IntPtr.Zero;

            // We get the document from the running doc table so that we can see if it is transient
            try
            {
                ErrorHandler.ThrowOnFailure(pRdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldMkDoc, out pHier, out id, out docdataForCookiePtr, out cookie));
            }
            finally
            {
                if (docdataForCookiePtr != IntPtr.Zero)
                    Marshal.Release(docdataForCookiePtr);
            }

            //Get the document info
            try
            {
                ErrorHandler.ThrowOnFailure(pRdt.GetDocumentInfo(cookie, out grfFlags, out readLocks, out editLocks, out doc, out pHier, out id, out docDataPtr));
            }
            finally
            {
                if (docDataPtr != IntPtr.Zero)
                    Marshal.Release(docDataPtr);
            }

            // Now see if the document is in the project. If not, we fail
            try
            {
                ErrorHandler.ThrowOnFailure(IsDocumentInProject(newMkDoc, out found, priority, out itemid));
                Debug.Assert(itemid != VSConstants.VSITEMID_NIL && itemid != VSConstants.VSITEMID_ROOT);
                hierPtr = Marshal.GetComInterfaceForObject(this, typeof(IVsUIHierarchy));
                // Now rename the document
                ErrorHandler.ThrowOnFailure(pRdt.RenameDocument(oldMkDoc, newMkDoc, hierPtr, itemid));
            }
            finally
            {
                if (hierPtr != IntPtr.Zero)
                    Marshal.Release(hierPtr);
            }

            //Change the caption if we are passed a window frame
            if (frame != null)
            {
                string caption = "%2";
                hr = frame.SetProperty((int)(__VSFPROPID.VSFPROPID_OwnerCaption), caption);
            }
            return hr;
        }
Пример #38
0
        public int OnAfterLastDocumentUnlock(IVsHierarchy pHier, uint itemid, string pszMkDocument, int fClosedWithoutSaving)
        {
            int found;
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            ErrorHandler.ThrowOnFailure(project.IsDocumentInProject(pszMkDocument, out found, priority, out itemid));

            if (found == 1  && NeedsNotify(pszMkDocument))
                AddWatcher(pszMkDocument);

            return VSConstants.S_OK;
        }
Пример #39
0
 public int IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) {
   _logger.LogHierarchy("IsDocumentInProject({0})", pszMkDocument);
   pfFound = 0;
   pitemid = 0U;
   if (pdwPriority != null && pdwPriority.Length >= 1)
     pdwPriority[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
   return 0;
 }
Пример #40
0
    private int OpenItemViaMiscellaneousProject(uint flags, string moniker, ref Guid rguidLogicalView, out IVsWindowFrame ppWindowFrame) {
      ppWindowFrame = null;

      var miscellaneousProject = VsShellUtilities.GetMiscellaneousProject(this._serviceProvider);
      int hresult = VSConstants.E_FAIL;
      if (miscellaneousProject != null &&
         _serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) is IVsUIShellOpenDocument) {
        var externalFilesManager = this._serviceProvider.GetService(typeof(SVsExternalFilesManager)) as IVsExternalFilesManager;
        externalFilesManager.TransferDocument(null, moniker, null);
        IVsProject ppProject;
        hresult = externalFilesManager.GetExternalFilesProject(out ppProject);
        if (ppProject != null) {
          int pfFound;
          uint pitemid;
          var pdwPriority = new VSDOCUMENTPRIORITY[1];
          hresult = ppProject.IsDocumentInProject(moniker, out pfFound, pdwPriority, out pitemid);
          if (pfFound == 1 && (int)pitemid != -1)
            hresult = ppProject.OpenItem(pitemid, ref rguidLogicalView, IntPtr.Zero, out ppWindowFrame);
        }
      }
      return hresult;
    }
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
           // SwitchDomainForRazorEngine();
            byte[] resultBytes;
            try
            {
                var model = new RazorModel();
                //set file name and namespace for model using
                model.DefaultNameSpace = wszDefaultNamespace;
                var info=new FileInfo(wszInputFilePath);
                if (info.Exists)
                {
                    model.FileName = info.Name;
                }
                int iFound;
                uint itemId;
                ProjectItem item;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(project);
                // this locates, and returns a handle to our source file, as a ProjectItem
                vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId);

                // if our source file was found in the project (which it should have been)
                if (iFound != 0 && itemId != 0)
                {
                    IServiceProvider oleSp;
                    vsProject.GetItemContext(itemId, out oleSp);
                    if (oleSp != null)
                    {
                        ServiceProvider sp = new ServiceProvider(oleSp);
                        // convert our handle to a ProjectItem
                        item = sp.GetService(typeof(ProjectItem)) as ProjectItem;
                    }
                    else
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                }
                else
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");

                var generator = new RazorGenerator(wszInputFilePath,bstrInputFileContents, model);
                generator.Init();
                //get extension from header file
                if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension))
                {
                    _extenstion = generator.RazorTemplate.OutPutExtension;
                }
                //generate code
                var result = generator.Render();
                resultBytes = Encoding.UTF8.GetBytes(result);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_OK;
            }
            catch (TemplateCompilationException tex)
            {
                //Display error in result template
                foreach (var compilerError in tex.CompilerErrors)
                {
                    pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint) compilerError.Line,
                        (uint) compilerError.Column);
                }
                var message = MRazorUtil.GetError(tex);
                resultBytes = Encoding.UTF8.GetBytes(message);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_FALSE;// Change to E_Fail will display error in error list
            }
            catch (Exception ex)
            {
                var messageBuilder =new StringBuilder( ex.Message);
                messageBuilder.AppendLine();
                if (ex.Source != null) messageBuilder.Append(ex.Source);
                messageBuilder.Append(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    messageBuilder.AppendLine();
                    messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace);
                }
                resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString());
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_FALSE;// Change to E_Fail will display error in error list
            }
            //finally
            //{
            //    //unload domain for unload dll loaded from InputDllFolder
            //    if (_domain != null) AppDomain.Unload(_domain);
            //}

        }
Пример #42
0
 int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
 {
     uint i = 0;
     foreach (string doc in children)
     {
         if (doc == pszMkDocument)
         {
             pfFound = 1;
             pitemid = i;
             return VSConstants.S_OK;
         }
         i++;
     }
     pitemid = VSConstants.VSITEMID_NIL;
     pfFound = 0;
     return VSConstants.S_OK;
 }
Пример #43
0
 /// <include file='doc\Project.uex' path='docs/doc[@for="ImageNames.IsDocumentInProject"]/*' />
 public virtual int IsDocumentInProject(string mkDoc, out int pfFound, VSDOCUMENTPRIORITY[] pri, out uint itemId)
 {
     CCITracing.TraceCall();
     if (pri != null && pri.Length >= 1)
     {
         pri[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
     }
     pfFound = 0;
     itemId = 0;
     HierarchyNode child = this.FindChild(mkDoc);
     if (child != null)
     {
         pfFound = 1;
         if (pri != null && pri.Length >= 1)
         {
             pri[0] = VSDOCUMENTPRIORITY.DP_Standard;
         }
         itemId = child.ID;
     }
     return NativeMethods.S_OK;
 }
Пример #44
0
        private bool TryGetItemIdInSharedHierarchyInternal(IVsHierarchy hierarchy, uint itemId, IVsHierarchy sharedHierarchy, out uint itemIdInSharedHierarchy)
        {
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];

            if (ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out var fullPath))
                && ErrorHandler.Succeeded(((IVsProject)sharedHierarchy).IsDocumentInProject(fullPath, out var found, priority, out itemIdInSharedHierarchy))
                && found != 0
                && itemIdInSharedHierarchy != (uint)VSConstants.VSITEMID.Nil)
            {
                return true;
            }

            itemIdInSharedHierarchy = (uint)VSConstants.VSITEMID.Nil;
            return false;
        }
Пример #45
0
        public int IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
        {
            pfFound = 0;
            pitemid = VSConstants.VSITEMID_NIL;
            pszMkDocument = pszMkDocument.ToLower();

            if (pszMkDocument.CompareTo(_projFile) == 0)
            {
                pfFound = 1;
                pitemid = VSConstants.VSITEMID_ROOT;
            }
            else
            {
                for (int iIndex = 0; iIndex < _items.Count; iIndex++)
                {
                    if (pszMkDocument.CompareTo(_items[iIndex]) == 0)
                    {
                        pfFound = 1;
                        pitemid = (uint)iIndex;
                        break;
                    }
                }
            }

            return VSConstants.S_OK;
        }
Пример #46
0
 void adjustAddFile(string fileName, IVsProject3 pro) {
   int pfFound; VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
   int retVal; uint dirId, newFileId;
   //Microsoft.VisualStudio.VSConstants.VSITEMID 
   //if (!File.Exists(fileName)) throw new Exception();
   //retVal = pro.IsDocumentInProject(fileName, out pfFound, pdwPriority, out newFileId);
   //if (retVal != 0) return;
   //if (pfFound != 1) { 
   //}
   retVal = pro.IsDocumentInProject(fileName, out pfFound, pdwPriority, out newFileId);
   VSADDRESULT[] addResArr = new VSADDRESULT[1];
   string[] fnarr = new string[] { fileName };
   //retVal = pro.AddItem(newFileId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, fileName, cFilesToOpen, fnarr, IntPtr.Zero, addResArr);
   //retVal = pro.AddItem(VSConstants.VSITEMID_ROOT, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, fileName, 1, fnarr, IntPtr.Zero, addResArr);
   retVal = pro.AddItem(newFileId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, fileName, 1, fnarr, IntPtr.Zero, addResArr);
   if (retVal != 0) return;
   //retVal = pro.IsDocumentInProject(fileName, out pfFound, pdwPriority, out newFileId);
   //retVal = pro.IsDocumentInProject(fileName, out pfFound, pdwPriority, out newFileId);
   if (retVal != 0) return;
   Guid guid = Guid.Empty; IVsWindowFrame frame = null;
   retVal = pro.OpenItem(newFileId, ref guid, IntPtr.Zero, out frame);
   if (frame != null) frame.Show();
 }
        /// <summary>
        /// Returns a list of controlled projects containing the specified file
        /// </summary>
        public IList<VSITEMSELECTION> GetControlledProjectsContainingFile(string file)
        {
            // Accumulate all the controlled projects that contain this file
            IList<VSITEMSELECTION> nodes = new List<VSITEMSELECTION>();

            foreach (IVsHierarchy pHier in _controlledProjects.Keys)
            {
                IVsHierarchy solHier = (IVsHierarchy)_sccProvider.GetService(typeof(SVsSolution));
                if (solHier == pHier)
                {
                    // This is the solution
                    if (file.ToLower().CompareTo(_sccProvider.GetSolutionFileName().ToLower()) == 0)
                    {
                        VSITEMSELECTION vsItem;
                        vsItem.itemid = VSConstants.VSITEMID_ROOT;
                        vsItem.pHier = null;
                        nodes.Add(vsItem);
                    }
                }
                else
                {
                    IVsProject2 pProject = pHier as IVsProject2;
                    // See if the file is member of this project
                    // Caveat: the IsDocumentInProject function is expensive for certain project types, 
                    // you may want to limit its usage by creating your own maps of file2project or folder2project
                    int fFound;
                    uint itemid;
                    VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                    if (pProject != null && pProject.IsDocumentInProject(file, out fFound, prio, out itemid) == VSConstants.S_OK && fFound != 0)
                    {
                        VSITEMSELECTION vsItem;
                        vsItem.itemid = itemid;
                        vsItem.pHier = pHier;
                        nodes.Add(vsItem);
                    }
                }
            }

            return nodes;
        }
Пример #48
0
        public override void OnExecute(CommandEventArgs e)
        {
            VisualGitMessageBox mb = new VisualGitMessageBox(e.Context);
            foreach (GitItem item in e.Selection.GetSelectedGitItems(false))
            {
                if (!item.Exists)
                    continue;

                try
                {
                    switch (e.Command)
                    {
                        case VisualGitCommand.ItemOpenVisualStudio:
                            IProjectFileMapper mapper = e.GetService<IProjectFileMapper>();

                            if (mapper.IsProjectFileOrSolution(item.FullPath))
                                goto case VisualGitCommand.ItemOpenSolutionExplorer;
                            if (item.IsDirectory)
                                goto case VisualGitCommand.ItemOpenFolder;

                            if (!item.IsFile || !item.Exists)
                                continue;

                            VsShellUtilities.OpenDocument(e.Context, item.FullPath);
                            break;
                        case VisualGitCommand.ItemOpenTextEditor:
                            {
                                IVsUIHierarchy hier;
                                IVsWindowFrame frame;
                                uint id;

                                if (!item.IsFile)
                                    continue;

                                VsShellUtilities.OpenDocument(e.Context, item.FullPath, VSConstants.LOGVIEWID_TextView, out hier, out id, out frame);
                            }
                            break;
                        case VisualGitCommand.ItemOpenFolder:
                            if (!item.IsDirectory)
                                System.Diagnostics.Process.Start(Path.GetDirectoryName(item.FullPath));
                            else
                                System.Diagnostics.Process.Start(item.FullPath);
                            break;
                        case VisualGitCommand.ItemOpenWindows:
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(item.FullPath);
                            psi.Verb = "open";
                            System.Diagnostics.Process.Start(psi);
                            break;

                        case VisualGitCommand.ItemOpenSolutionExplorer:
                            IVsUIHierarchyWindow hierWindow = VsShellUtilities.GetUIHierarchyWindow(e.Context, new Guid(ToolWindowGuids80.SolutionExplorer));

                            IVsProject project = VsShellUtilities.GetProject(e.Context, item.FullPath) as IVsProject;

                            if (hierWindow != null)
                            {
                                int found;
                                uint id;
                                VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                                if (project != null && ErrorHandler.Succeeded(project.IsDocumentInProject(item.FullPath, out found, prio, out id)) && found != 0)
                                {
                                    hierWindow.ExpandItem(project as IVsUIHierarchy, id, EXPANDFLAGS.EXPF_SelectItem);
                                }
                                else if (string.Equals(item.FullPath, e.Selection.SolutionFilename, StringComparison.OrdinalIgnoreCase))
                                    hierWindow.ExpandItem(e.GetService<IVsUIHierarchy>(typeof(SVsSolution)), VSConstants.VSITEMID_ROOT, EXPANDFLAGS.EXPF_SelectItem);

                                // Now try to activate the solution explorer
                                IVsWindowFrame solutionExplorer;
                                Guid solutionExplorerGuid = new Guid(ToolWindowGuids80.SolutionExplorer);
                                IVsUIShell shell = e.GetService<IVsUIShell>(typeof(SVsUIShell));

                                if (shell != null)
                                {
                                    shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorerGuid, out solutionExplorer);

                                    if (solutionExplorer != null)
                                        solutionExplorer.Show();
                                }

                            }
                            break;
                    }
                }
                catch (IOException ee)
                {
                    e.GetService<IVisualGitErrorHandler>().OnWarning(ee);
                }
                catch (COMException ee)
                {
                    e.GetService<IVisualGitErrorHandler>().OnWarning(ee);
                }
                catch (InvalidOperationException ee)
                {
                    e.GetService<IVisualGitErrorHandler>().OnWarning(ee);
                }
                catch (System.ComponentModel.Win32Exception ee)
                {
                    e.GetService<IVisualGitErrorHandler>().OnWarning(ee);
                }

            }
        }
Пример #49
0
    private void IsDocumentInAnotherProject(string originalPath, out IVsHierarchy hierOpen, out uint itemId, out int isDocInProj) {
      var vsSolution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
      var rguidEnumOnlyThisType = Guid.Empty;
      IEnumHierarchies ppenum;
      itemId = uint.MaxValue;
      hierOpen = null;
      isDocInProj = 0;
      vsSolution.GetProjectEnum((int)__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, ref rguidEnumOnlyThisType, out ppenum);
      if (ppenum == null)
        return;

      ppenum.Reset();
      uint pceltFetched = 1U;
      var rgelt = new IVsHierarchy[1];
      ppenum.Next(1U, rgelt, out pceltFetched);
      while ((int)pceltFetched == 1) {
        var vsProject = rgelt[0] as IVsProject;
        var pdwPriority = new VSDOCUMENTPRIORITY[1];
        uint pitemid;
        vsProject.IsDocumentInProject(originalPath, out isDocInProj, pdwPriority, out pitemid);
        if (isDocInProj == 1) {
          hierOpen = rgelt[0];
          itemId = pitemid;
          break;
        }
        ppenum.Next(1U, rgelt, out pceltFetched);
      }
    }
Пример #50
0
 /// <include file='doc\Project.uex' path='docs/doc[@for="ImageNames.IsDocumentInProject"]/*' />
 public virtual int IsDocumentInProject(string mkDoc, out int pfFound, VSDOCUMENTPRIORITY[] pri, out uint itemId){
   pri[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
   pfFound = 0;
   itemId = 0;
   HierarchyNode child = mkDoc == this.FullPath ? this : this.FindChild(mkDoc);
   if (child != null){
     pfFound = 1;
     pri[0] = VSDOCUMENTPRIORITY.DP_Standard;
     itemId = child.ID;
   }
   return 0;
 }
Пример #51
0
 int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) {
     return _innerProject.IsDocumentInProject(pszMkDocument, out pfFound, pdwPriority, out pitemid);
 }
Пример #52
0
        public override void OnExecute(CommandEventArgs e)
        {
            List<SvnItem> toDelete = new List<SvnItem>(e.Selection.GetSelectedSvnItems(true));

            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            string body;

            // We do as if we are Visual Studio here: Same texts, same behavior (same chance on data loss)
            if (toDelete.Count == 1)
                body = string.Format(CommandStrings.XWillBeDeletedPermanently, toDelete[0].Name);
            else
                body = CommandStrings.TheSelectedItemsWillBeDeletedPermanently;

            if (DialogResult.OK != mb.Show(body, "", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
                return; // No delete

            int hr = VSConstants.S_OK;
            foreach (SvnItem item in toDelete)
            {
                {
                    IVsUIHierarchy hier;
                    uint id;
                    IVsWindowFrame frame;

                    if (VsShellUtilities.IsDocumentOpen(e.Context, item.FullPath, Guid.Empty, out hier, out id, out frame))
                    {
                        hr = frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                        if (!ErrorHandler.Succeeded(hr))
                            break; // Show error and cancel further actions
                    }
                }

                try
                {
                    if (item.IsVersioned)
                    {
                        using (SvnClient cl = e.GetService<ISvnClientPool>().GetNoUIClient())
                        {
                            SvnDeleteArgs da = new SvnDeleteArgs();
                            da.Force = true;
                            cl.Delete(item.FullPath, da);
                        }
                    }
                    else if (item.IsFile)
                        File.Delete(item.FullPath);
                    else if (item.IsDirectory)
                        Directory.Delete(item.FullPath, true); // Recursive delete!!
                }
                finally
                {
                    // TODO: Notify the working copy explorer here!
                    // (Maybe via one of these methods below)

                    e.GetService<IFileStatusCache>().MarkDirtyRecursive(item.FullPath);
                    e.GetService<IFileStatusMonitor>().ScheduleGlyphUpdate(item.FullPath);
                }

                // Ok, now remove the file from projects

                IProjectFileMapper pfm = e.GetService<IProjectFileMapper>();

                List<SvnProject> projects = new List<SvnProject>(pfm.GetAllProjectsContaining(item.FullPath));

                foreach (SvnProject p in projects)
                {
                    IVsProject2 p2 = p.RawHandle as IVsProject2;

                    if (p2 == null)
                        continue;

                    VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                    int found;
                    uint id;
                    if (!ErrorHandler.Succeeded(p2.IsDocumentInProject(item.FullPath, out found, prio, out id)) || found == 0)
                        continue; // Probably already removed (mapping out of synch?)

                    hr = p2.RemoveItem(0, id, out found);

                    if (!ErrorHandler.Succeeded(hr))
                        break;
                }
            }

            if (!ErrorHandler.Succeeded(hr))
                mb.Show(Marshal.GetExceptionForHR(hr).Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        public bool IsFileInProject(Project project, string file)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (string.IsNullOrWhiteSpace(file))
            {
                throw new ArgumentNullException(nameof(file));
            }

            IVsSolution solution = this.serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            Debug.Assert(solution != null, "Cannot find SVsSolution");

            IVsHierarchy projectHierarchy;
            if (ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy)))
            {
                IVsProject vsProject = projectHierarchy as IVsProject;
                int pfFound;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
                uint itemId;
                if (ErrorHandler.Succeeded(vsProject.IsDocumentInProject(file, out pfFound, pdwPriority, out itemId)) && pfFound != 0)
                {
                    return true;
                }
            }

            return false;
        }
        int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
        {
            pfFound = 0;
            pitemid = 0;

            if (this.Files.TryGetValue(pszMkDocument, out pitemid))
            {
                pfFound = 1;
            }
            return VSConstants.S_OK;
        }
Пример #55
0
        public virtual int IsDocumentInProject(string mkDoc, out int found, VSDOCUMENTPRIORITY[] pri, out uint itemId)
        {
            CCITracing.TraceCall();
            if (pri != null && pri.Length >= 1)
            {
                pri[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
            }
            found = 0;
            itemId = 0;

            // If it is the project file just return.
            if (NativeMethods.IsSamePath(mkDoc, this.GetMkDocument()))
            {
                found = 1;
                itemId = VSConstants.VSITEMID_ROOT;
            }
            else
            {
                HierarchyNode child = this.FindChild(mkDoc);
                if (child != null)
                {
                    found = 1;
                    itemId = child.ID;
                }
            }

            if (found == 1)
            {
                if (pri != null && pri.Length >= 1)
                {
                    pri[0] = VSDOCUMENTPRIORITY.DP_Standard;
                }
            }

            return VSConstants.S_OK;
        }
Пример #56
0
 public int IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
 {
     throw new NotImplementedException();
 }
Пример #57
0
        private string PathOfCookie(uint docCookie)
        {
            uint pgrfRDTFlags;
            uint pdwReadLocks;
            uint pdwEditLocks;
            string result;
            IVsHierarchy ppHier;
            uint pitemid;
            IntPtr ppunkDocData;

            ErrorHandler.ThrowOnFailure(vsRDT.GetDocumentInfo(
                docCookie,
                out pgrfRDTFlags,
                out pdwReadLocks,
                out pdwEditLocks,
                out result,
                out ppHier,
                out pitemid,
                out ppunkDocData
            ));
            //if (project == (IVsProject)ppHier)
            int found;
            uint itemid;
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            ErrorHandler.ThrowOnFailure(project.IsDocumentInProject(result, out found, priority, out itemid));
            if (found == 1)
                return result;
            return null;
        }
Пример #58
0
 public int IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Пример #59
0
		int IVsProject3.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid)
		{
			pfFound = 0;
			pitemid = 0;
			if (pdwPriority != null)
			{
				pdwPriority[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
			}

			// Try to find the item in our hierarchy.
			Node node = this.GetNodeFromName(pszMkDocument);
			if (node != null)
			{
				pfFound = 1;
				pitemid = node.HierarchyId;
				if (pdwPriority != null)
				{
					pdwPriority[0] = VSDOCUMENTPRIORITY.DP_Standard;
				}
			}

			return NativeMethods.S_OK;
		}
Пример #60
0
        /// <summary>
        /// This will add a file to the misc folders without actually opening the document in 
        /// Visual Studio
        /// </summary>
        private void CreateHierarchy(string moniker, out IVsUIHierarchy vsUiHierarchy, out uint itemId)
        {
            vsUiHierarchy = null;
            itemId = VSConstants.VSITEMID_NIL;

            var vsExternalFilesManager = _vsServiceProvider.GetService<SVsExternalFilesManager, IVsExternalFilesManager>();

            int defaultPosition;
            IVsWindowFrame dummyWindowFrame;
            uint flags = (uint)_VSRDTFLAGS.RDT_NonCreatable | (uint)_VSRDTFLAGS.RDT_PlaceHolderDoc;
            var hr = vsExternalFilesManager.AddDocument(
                dwCDW: flags,
                pszMkDocument: moniker,
                punkDocView: IntPtr.Zero,
                punkDocData: IntPtr.Zero,
                rguidEditorType: Guid.Empty,
                pszPhysicalView: null,
                rguidCmdUI: Guid.Empty,
                pszOwnerCaption: moniker,
                pszEditorCaption: null,
                pfDefaultPosition: out defaultPosition,
                ppWindowFrame: out dummyWindowFrame);
            ErrorHandler.ThrowOnFailure(hr);

            // Get the hierarchy for the document we added to the miscellaneous files project
            IVsProject vsProject;
            hr = vsExternalFilesManager.GetExternalFilesProject(out vsProject);
            ErrorHandler.ThrowOnFailure(hr);

            int found;
            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            hr = vsProject.IsDocumentInProject(moniker, out found, priority, out itemId);
            ErrorHandler.ThrowOnFailure(hr);
            if (0 == found || VSConstants.VSITEMID_NIL == itemId)
            {
                throw new Exception("Could not find in project");
            }

            vsUiHierarchy = (IVsUIHierarchy)vsProject;
        }