Пример #1
0
		public VsSolutionSelection (
			[Import (ContractNames.Interop.SolutionExplorerWindow)] IVsUIHierarchyWindow hierarchyWindow,
			IVsHierarchyItemManager hierarchyManager,
			IAsyncManager asyncManager)
		{
			this.hierarchyWindow = hierarchyWindow;
			this.hierarchyManager = hierarchyManager;
			this.asyncManager = asyncManager;
		}
 private void CollapseHierarchyItems(IVsUIHierarchyWindow toolWindow, IVsHierarchy hierarchy, uint itemid, bool hierIsSolution
     , string[] captions)
 {
     IntPtr ptr;
     uint num2;
     Guid gUID = typeof(IVsHierarchy).GUID;
     if ((hierarchy.GetNestedHierarchy(itemid, ref gUID, out ptr, out num2) == 0) && (IntPtr.Zero != ptr))
     {
         IVsHierarchy objectForIUnknown = Marshal.GetObjectForIUnknown(ptr) as IVsHierarchy;
         Marshal.Release(ptr);
         if (objectForIUnknown != null)
         {
             this.CollapseHierarchyItems(toolWindow, objectForIUnknown, num2, false, captions);
         }
     }
     else
     {
         object obj2;
         if (!hierIsSolution)
         {
             string canonicalname;
             object captionobj;
             hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_Caption, out captionobj);
             var caption = (string)captionobj;
             if (captions.Contains(caption))
             {
                 hierarchy.GetCanonicalName(itemid, out canonicalname);
                 ErrorHandler.ThrowOnFailure(toolWindow.ExpandItem(hierarchy as IVsUIHierarchy, itemid, EXPANDFLAGS.EXPF_CollapseFolder));
             }
         }
         if (hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_FirstVisibleChild, out obj2) == 0)
         {
             uint itemId = this.GetItemId(obj2);
             while (itemId != uint.MaxValue)
             {
                 this.CollapseHierarchyItems(toolWindow, hierarchy, itemId, false, captions);
                 int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_NextVisibleSibling, out obj2);
                 if (hr == 0)
                 {
                     itemId = this.GetItemId(obj2);
                 }
                 else
                 {
                     ErrorHandler.ThrowOnFailure(hr);
                     return;
                 }
             }
         }
     }
 }
Пример #3
0
        private static async Task CollapseVsHierarchyItemAsync(VsHierarchyItem vsHierarchyItem, IVsUIHierarchyWindow vsHierarchyWindow)
        {
            if (vsHierarchyItem == null ||
                vsHierarchyWindow == null)
            {
                return;
            }

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            vsHierarchyWindow.ExpandItem(AsVsUIHierarchy(vsHierarchyItem), vsHierarchyItem.VsItemID, EXPANDFLAGS.EXPF_CollapseFolder);
        }
Пример #4
0
        private static async Task <bool> IsVsHierarchyItemExpandedAsync(VsHierarchyItem hierarchyItem, IVsUIHierarchyWindow uiWindow)
        {
            if (!await hierarchyItem.IsExpandableAsync())
            {
                return(false);
            }

            const uint expandedStateMask = (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded;
            uint       itemState;

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            uiWindow.GetItemState(AsVsUIHierarchy(hierarchyItem), hierarchyItem.VsItemID, expandedStateMask, out itemState);
            return((__VSHIERARCHYITEMSTATE)itemState == __VSHIERARCHYITEMSTATE.HIS_Expanded);
        }
Пример #5
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Higlights the specified node with bold font.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void BoldNode(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                             uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_BoldItem);
 }
        public static FileInfo LookingForSelectedItem(IServiceProvider serviceProvider)
        {
            IVsUIHierarchyWindow hierarchyWindow = VsShellUtilities.GetUIHierarchyWindow(serviceProvider,
                                                                                         VSConstants.StandardToolWindows.SolutionExplorer);

            ThreadHelper.ThrowIfNotOnUIThread();

            var pane = hierarchyWindow as WindowPane;

            if (pane == null)
            {
                throw new FileNotFoundException("Unable to find the items full path");
            }

            var paneContent = pane.Content as Panel;

            if (paneContent == null || paneContent.Children.Count == 0)
            {
                throw new FileNotFoundException("Unable to find the items full path");
            }

            foreach (ContentPresenter contentPresenter in paneContent.Children)
            {
                try
                {
                    if (contentPresenter == null)
                    {
                        continue;
                    }

                    var listBox = contentPresenter.Content.GetType().GetProperties().Single(p => p.Name == "TreeView" &&
                                                                                            p.PropertyType.FullName == "Microsoft.VisualStudio.PlatformUI.SolutionPivotTreeView")
                                  .GetValue(contentPresenter.Content) as ListBox;

                    if (listBox.SelectedItem == null)
                    {
                        continue;
                    }

                    var selectedItemNode = listBox.SelectedItem as Microsoft.Internal.VisualStudio.PlatformUI.IVirtualizingTreeNode;
                    if (selectedItemNode == null)
                    {
                        continue;
                    }

                    var sourceItem = selectedItemNode.Item.GetType().GetProperties().Single(p => p.Name == "SourceItem")
                                     .GetValue(selectedItemNode.Item);

                    var canonicalName = sourceItem.GetType().GetProperties().Single(p => p.Name == "CanonicalName")
                                        .GetValue(sourceItem) as string;

                    return(new FileInfo(canonicalName));
                }
                catch
                {
                    continue;
                }
            }

            throw new FileNotFoundException("Unable to find the items full path");
        }
        /// <summary>
        /// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
        /// </summary>
        /// <param name="oldFileName">The old file name.</param>
        /// <param name="newFileName">The new file name</param>
        /// <param name="newParentId">The new parent id of the item.</param>
        /// <returns>The newly added FileNode.</returns>
        /// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
        protected virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
        {
            if (string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
            {
                // We do not want to rename the same file
                return(null);
            }

            this.OnItemDeleted();
            this.Parent.RemoveChild(this);

            // Since this node has been removed all of its state is zombied at this point
            // Do not call virtual methods after this point since the object is in a deleted state.

            string[] file = new string[1];
            file[0] = newFileName;
            VSADDRESULT[] result    = new VSADDRESULT[1];
            Guid          emptyGuid = Guid.Empty;

            ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result));
            FileNode childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;

            Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
            // Update the itemid to the newly added.
            this.ID = childAdded.ID;

            // Remove the item created by the add item. We need to do this otherwise we will have two items.
            // Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
            // What we want to achieve here is to reuse the existing build item.
            // We want to link to the newly created node to the existing item node and addd the new include.

            //temporarily keep properties from new itemnode since we are going to overwrite it
            string newInclude  = childAdded.ItemNode.Item.Include;
            string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);

            childAdded.ItemNode.RemoveFromProjectFile();

            // Assign existing msbuild item to the new childnode
            childAdded.ItemNode              = this.ItemNode;
            childAdded.ItemNode.Item.Name    = this.ItemNode.ItemName;
            childAdded.ItemNode.Item.Include = newInclude;
            if (!string.IsNullOrEmpty(dependentOf))
            {
                childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
            }
            childAdded.ItemNode.RefreshProperties();

            //Update the new document in the RDT.
            DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);

            //Select the new node in the hierarchy
            IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);

            uiWindow.ExpandItem(this.ProjectMgr, this.ID, EXPANDFLAGS.EXPF_SelectItem);

            //Update FirstChild
            childAdded.FirstChild = this.FirstChild;

            //Update ChildNodes
            SetNewParentOnChildNodes(childAdded);
            RenameChildNodes(childAdded);

            return(childAdded);
        }
Пример #8
0
 internal SessionsNode(IServiceProvider serviceProvider, IVsUIHierarchyWindow window)
 {
     _serviceProvider = serviceProvider;
     _window          = window;
 }
Пример #9
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Expands the parents of the specified node to show the node
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void ExpandParents(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                                  uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_ExpandParentsToShowItem);
 }
Пример #10
0
        public void Dispose()
        {
            if (_solutionExplorer2 != null)
            {
                try
                {
                    _solutionExplorer2.Unadvise(_cookie);
                }
                catch { /* Probably unclean shutdown */ }
                _solutionExplorer2 = null;
            }

            _solutionExplorer = null;
            _solutionExplorer2 = null;
            _tree = null;
        }
Пример #11
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Finds the common selection.
 /// </summary>
 /// <param name="window">The window.</param>
 /// <param name="commonHier">The common hier.</param>
 // --------------------------------------------------------------------------------------------
 public static int FindCommonSelectionRoot(this IVsUIHierarchyWindow window,
                                           out IVsUIHierarchy commonHier)
 {
     return(window.FindCommonSelectedHierarchy(
                (uint)__VSCOMHIEROPTIONS.COMHIEROPT_AllowHiddenRoot, out commonHier));
 }
Пример #12
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Collapses the specified hierarchy item.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void CollapseNode(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                                 uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_CollapseFolder);
 }
Пример #13
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Returns the state or appearance of the hierarchy.
 /// </summary>
 /// <param name="window">The hierarchy window.</param>
 /// <param name="hier">The hierarchy instance.</param>
 /// <param name="id">The id of the hierarchy node.</param>
 /// <param name="statemask">The mask to check the state.</param>
 /// <param name="result">The state flags of the specified item.</param>
 // --------------------------------------------------------------------------------------------
 public static void GetNodeState(this IVsUIHierarchyWindow window,
                                 IVsUIHierarchy hier, uint id, uint statemask, out uint result)
 {
     window.GetItemState(hier, id, statemask, out result);
 }
Пример #14
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Starts editing of the specified node label.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void EditNodeLabel(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                                  uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_EditItemLabel);
 }
Пример #15
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Removes Cut highlighting from the specified node.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void UnCutHighlightNode(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                                       uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_UnCutHighlightItem);
 }
Пример #16
0
        private static void CollapseVsHierarchyItem(VsHierarchyItem vsHierarchyItem, IVsUIHierarchyWindow vsHierarchyWindow)
        {
            if (vsHierarchyItem == null || vsHierarchyWindow == null)
            {
                return;
            }

            vsHierarchyWindow.ExpandItem(vsHierarchyItem.UIHierarchy(), vsHierarchyItem.VsItemID, EXPANDFLAGS.EXPF_CollapseFolder);
        }
Пример #17
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Adds a new node to the current selection.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node.</param>
 /// <param name="id">The id of the node.</param>
 // --------------------------------------------------------------------------------------------
 public static void AddSelectNode(this IVsUIHierarchyWindow window, IVsUIHierarchy node,
                                  uint id)
 {
     ExpandItem(window, node, id, EXPANDFLAGS.EXPF_SelectItem |
                EXPANDFLAGS.EXPF_AddSelectItem);
 }
Пример #18
0
        private static bool IsVsHierarchyItemExpanded(VsHierarchyItem hierarchyItem, IVsUIHierarchyWindow uiWindow)
        {
            if (!hierarchyItem.IsExpandable())
            {
                return false;
            }

            const uint expandedStateMask = (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded;
            uint itemState;

            uiWindow.GetItemState(hierarchyItem.UIHierarchy(), hierarchyItem.VsItemID, expandedStateMask, out itemState);
            return ((__VSHIERARCHYITEMSTATE)itemState == __VSHIERARCHYITEMSTATE.HIS_Expanded);
        }
Пример #19
0
 internal SessionsNode(IServiceProvider serviceProvider, IVsUIHierarchyWindow window) {
     _serviceProvider = serviceProvider;
     _window = window;
 }
Пример #20
0
 internal SessionsNode(IVsUIHierarchyWindow window)
 {
     _window = window;
 }
Пример #21
0
        /// <summary>
        ///  After a drop or paste, will use the dwEffects
        ///  to determine whether we need to clean up the source nodes or not. If
        ///  justCleanup is set, it only does the cleanup work.
        /// </summary>
        internal void CleanupSelectionDataObject(bool dropped, bool cut, bool moved, bool justCleanup)
        {
            if (this.ItemsDraggedOrCutOrCopied == null || this.ItemsDraggedOrCutOrCopied.Count == 0)
            {
                return;
            }

            try
            {
                IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);
                foreach (HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
                {
                    if ((moved && (cut || dropped) && !justCleanup))
                    {
                        // do not close it if the doc is dirty or we do not own it
                        bool isDirty, isOpen, isOpenedByUs;
                        uint docCookie;
                        IVsPersistDocData ppIVsPersistDocData;
                        DocumentManager   manager = node.GetDocumentManager();
                        if (manager != null)
                        {
                            manager.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData);
                            if (isDirty || (isOpen && !isOpenedByUs))
                            {
                                continue;
                            }

                            // close it if opened
                            if (isOpen)
                            {
                                manager.Close(__FRAMECLOSE.FRAMECLOSE_NoSave);
                            }
                        }

                        node.Remove(true);
                    }
                    else if (w != null)
                    {
                        ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, EXPANDFLAGS.EXPF_UnCutHighlightItem));
                    }
                }
            }
            finally
            {
                try
                {
                    // Now delete the memory allocated by the packaging of datasources.
                    // If we just did a cut, or we are told to cleanup, then we need to free the data object. Otherwise, we leave it
                    // alone so that you can continue to paste the data in new locations.
                    if (moved || cut || justCleanup)
                    {
                        this.ItemsDraggedOrCutOrCopied.Clear();
                        this.CleanAndFlushClipboard();
                    }
                }
                finally
                {
                    this.dropDataType = DropDataType.None;
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
        /// </summary>
        /// <param name="oldFileName">The old file name.</param>
        /// <param name="newFileName">The new file name</param>
        /// <param name="newParentId">The new parent id of the item.</param>
        /// <returns>The newly added FileNode.</returns>
        /// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
        public virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
        {
            if (string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
            {
                // We do not want to rename the same file
                return(null);
            }

            string[] file = new string[1];
            file[0] = newFileName;
            VSADDRESULT[] result    = new VSADDRESULT[1];
            Guid          emptyGuid = Guid.Empty;

            FileNode childAdded      = null;
            string   originalInclude = this.ItemNode.Item.UnevaluatedInclude;

            return(Transactional.Try(
                       // Action
                       () =>
            {
                // It's unfortunate that MPF implements rename in terms of AddItemWithSpecific. Since this
                // is the case, we have to pass false to prevent AddITemWithSpecific to fire Add events on
                // the IVsTrackProjectDocuments2 tracker. Otherwise, clients listening to this event
                // (SCCI, for example) will be really confused.
                using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
                {
                    var currentId = this.ID;

                    // actual deletion is delayed until all checks are passed
                    Func <uint> getIdOfExistingItem =
                        () =>
                    {
                        this.OnItemDeleted();
                        this.Parent.RemoveChild(this);
                        return currentId;
                    };

                    // raises OnItemAdded inside
                    ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result, false, getIdOfExistingItem));
                    childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;
                    Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
                }
            },
                       // Compensation
                       () =>
            {
                // it failed, but 'this' is dead and 'childAdded' is here to stay, so fix the latter back
                using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
                {
                    childAdded.ItemNode.Rename(originalInclude);
                    childAdded.ItemNode.RefreshProperties();
                }
            },

                       // Continuation
                       () =>
            {
                // Since this node has been removed all of its state is zombied at this point
                // Do not call virtual methods after this point since the object is in a deleted state.

                // Remove the item created by the add item. We need to do this otherwise we will have two items.
                // Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
                // What we want to achieve here is to reuse the existing build item.
                // We want to link to the newly created node to the existing item node and addd the new include.

                //temporarily keep properties from new itemnode since we are going to overwrite it
                string newInclude = childAdded.ItemNode.Item.UnevaluatedInclude;
                string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
                childAdded.ItemNode.RemoveFromProjectFile();

                // Assign existing msbuild item to the new childnode
                childAdded.ItemNode = this.ItemNode;
                childAdded.ItemNode.Item.ItemType = this.ItemNode.ItemName;
                childAdded.ItemNode.Item.Xml.Include = newInclude;
                if (!string.IsNullOrEmpty(dependentOf))
                {
                    childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
                }
                childAdded.ItemNode.RefreshProperties();

                // Extensibilty events has rename
                this.ProjectMgr.ExtensibilityEventsHelper.FireItemRenamed(childAdded, Path.GetFileName(originalInclude));

                //Update the new document in the RDT.
                try
                {
                    DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);

                    // The current automation node is renamed, but the hierarchy ID is now pointing to the old item, which
                    // is invalid. Update it.
                    this.ID = childAdded.ID;

                    //Update FirstChild
                    childAdded.FirstChild = this.FirstChild;

                    //Update ChildNodes
                    SetNewParentOnChildNodes(childAdded);
                    RenameChildNodes(childAdded);

                    return childAdded;
                }
                finally
                {
                    //Select the new node in the hierarchy
                    IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
                    uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, childAdded.ID, EXPANDFLAGS.EXPF_SelectItem);
                }
            }));
        }
Пример #23
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Expands the specified hierarchy item.
 /// </summary>
 /// <param name="window">The hierarchy window hosting the item.</param>
 /// <param name="node">The hierarchy of the node to expand.</param>
 /// <param name="id">The id of the node.</param>
 /// <param name="flags">Flags specifying how to expand the node.</param>
 // --------------------------------------------------------------------------------------------
 private static void ExpandItem(IVsUIHierarchyWindow window, IVsUIHierarchy node, uint id, 
     EXPANDFLAGS flags)
 {
     if (window == null) return;
       if (node == null) throw new ArgumentNullException("node");
       ErrorHandler.ThrowOnFailure(window.ExpandItem(node, id, flags));
 }
Пример #24
0
        public void TestAutomationOnProjectItem()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination = Path.Combine(TestContext.TestDir, TestContext.TestName);
                Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject;
                Assert.IsNotNull(automation, "Failed to create a project using automation");

                ProjectNode project = automation.Project;

                // Get the AssemblyInfo.cs, try to open it and then ask using automation that it is opened.
                EnvDTE.ProjectItem item = automation.ProjectItems.Item("AssemblyInfo.cs");
                Assert.IsNotNull(item, "Could not retrieve AssemblyInfo.cs");

                EnvDTE.Window window = item.Open(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsNotNull(window, "Could not open the AssemblyInfo.cs");
                window.Activate();

                bool isOpen = item.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsTrue(isOpen, "The AssemblyInfo.cs file should have been opened");

                // Now save it
                item.Save("");

                Assert.IsTrue(item.Saved, "The renamed AssemblyInfo.cs has not been saved");

                // Get the Document
                EnvDTE.Document document = item.Document;
                Assert.IsNotNull(document, "Could not retrieve the document object");
                Assert.IsTrue(document.Name == "AssemblyInfo.cs", "The document for the file item is incorrect. It's name should be AssemblyInfo.cs");

                // Try the properties on a nested item
                EnvDTE.ProjectItem nestedProject     = automation.ProjectItems.Item("ANestedProject");
                EnvDTE.ProjectItem nestedProjectItem = nestedProject.ProjectItems.Item("Program.cs");
                EnvDTE.Properties nesteditemsProps   = nestedProjectItem.Properties;
                EnvDTE.Property nestedItemProperty   = nesteditemsProps.Item("BuildAction");
                Assert.IsNotNull(nestedItemProperty, "Could not retrieve the BuildAction property from the nested project item");
                nestedItemProperty.Value = BuildAction.Content;
                Assert.AreEqual((BuildAction)nestedItemProperty.Value, BuildAction.Content);

                // Now try the properties on the top project item
                EnvDTE.Properties props = item.Properties;
                Assert.IsNotNull(props, "Could not retrieve the BuildAction property from the nested project item");

                EnvDTE.Property itemProperty = props.Item("BuildAction");
                Assert.IsNotNull(itemProperty, "Could not retrieve the BuildAction property from the nested project item");
                Assert.IsFalse(itemProperty is OANullProperty, "Could not retrieve the BuildAction property from the nested project item");
                itemProperty.Value = BuildAction.Content;
                Assert.AreEqual(itemProperty.Value, BuildAction.Content);

                // Now save as
                Assert.IsTrue(item.SaveAs("AssemblyInfo1.cs"), "The file AssemblyInfo.cs could not be reanmed to AssemblyInfo1.cs");
                Assert.IsTrue(item.Name == "AssemblyInfo1.cs", "File item has been renamed to AssemblyInfo1.cs but the Name property has not");

                // Now try the Program.cs. That should not be opened
                EnvDTE.ProjectItem item1 = automation.ProjectItems.Item("Program.cs");

                Assert.IsNotNull(item1, "Could not retrieve AssemblyInfo.cs");

                isOpen = item1.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());

                Assert.IsFalse(isOpen, "The Program.cs should not have been opened");

                // Now get the Reference folder as a project item and expand it.
                EnvDTE.ProjectItem references = automation.ProjectItems.Item("References");
                references.ExpandView();

                // Check that actually it was expanded.
                IVsUIHierarchyWindow uiHierarchy     = VsShellUtilities.GetUIHierarchyWindow(project.Site, HierarchyNode.SolutionExplorer);
                System.Reflection.MethodInfo mi      = typeof(ProjectNode).GetMethod("FindChild", BindingFlags.NonPublic | BindingFlags.Instance);
                ReferenceContainerNode containerNode = (ReferenceContainerNode)mi.Invoke(project, new object[] { "References" });

                __VSHIERARCHYITEMSTATE state;
                uint stateAsInt;
                uiHierarchy.GetItemState(project, (uint)containerNode.ID, (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded, out stateAsInt);
                state = (__VSHIERARCHYITEMSTATE)stateAsInt;
                Assert.IsTrue(state == __VSHIERARCHYITEMSTATE.HIS_Expanded, "The References folder has not been expanded");
            });
        }
Пример #25
0
        private VSITEMSELECTION[] GetSelectedNodes(IVsUIHierarchyWindow toolWindow)
        {
            ErrorUtilities.VerifyThrowArgumentNull((object)toolWindow, "toolWindow");
            uint   pitemid = uint.MaxValue;
            IntPtr ppHier  = IntPtr.Zero;

            VSITEMSELECTION[] vsitemselectionArray = (VSITEMSELECTION[])null;
            try
            {
                IVsMultiItemSelect ppMIS;
                int currentSelection = toolWindow.GetCurrentSelection(out ppHier, out pitemid, out ppMIS);
                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(currentSelection);
                if (currentSelection == 0)
                {
                    if ((int)pitemid == -3 && ppMIS != null)
                    {
                        uint pcItems;
                        int  pfSingleHierarchy;
                        int  selectionInfo = ppMIS.GetSelectionInfo(out pcItems, out pfSingleHierarchy);
                        Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(selectionInfo);
                        if (pcItems > 0U)
                        {
                            if (selectionInfo == 0)
                            {
                                VSITEMSELECTION[] rgItemSel = new VSITEMSELECTION[pcItems];
                                for (int index = 0; (long)index < (long)pcItems; ++index)
                                {
                                    rgItemSel[index].itemid = uint.MaxValue;
                                    rgItemSel[index].pHier  = (IVsHierarchy)null;
                                }
                                int selectedItems = ppMIS.GetSelectedItems(0U, pcItems, rgItemSel);
                                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(selectedItems);
                                if (selectedItems == 0)
                                {
                                    vsitemselectionArray = rgItemSel;
                                }
                            }
                        }
                    }
                    else if ((int)pitemid != -3)
                    {
                        if (ppHier != IntPtr.Zero)
                        {
                            IVsHierarchy objectForIunknown = Marshal.GetObjectForIUnknown(ppHier) as IVsHierarchy;
                            vsitemselectionArray = new VSITEMSELECTION[1]
                            {
                                new VSITEMSELECTION()
                                {
                                    itemid = pitemid,
                                    pHier  = objectForIunknown
                                }
                            };
                        }
                    }
                }
            }
            finally
            {
                if (ppHier != IntPtr.Zero)
                {
                    Marshal.Release(ppHier);
                }
            }
            return(vsitemselectionArray ?? new VSITEMSELECTION[0]);
        }
Пример #26
0
        /// <summary>
        /// Returns a dataobject from selected nodes
        /// </summary>
        /// <param name="cutHighlightItems">boolean that defines if the selected items must be cut</param>
        /// <returns>data object for selected items</returns>
        internal virtual DataObject PackageSelectionDataObject(bool cutHighlightItems)
        {
            this.CleanupSelectionDataObject(false, false, false);
            StringBuilder sb = new StringBuilder();

            DataObject dataObject = null;

            try
            {
                IList <HierarchyNode> selectedNodes = this.GetSelectedNodes();
                if (selectedNodes != null)
                {
                    this.InstantiateItemsDraggedOrCutOrCopiedList();

                    StringBuilder selectionContent = null;

                    // If there is a selection package the data
                    if (selectedNodes.Count > 1)
                    {
                        foreach (HierarchyNode node in selectedNodes)
                        {
                            selectionContent = node.PrepareSelectedNodesForClipBoard();
                            if (selectionContent != null)
                            {
                                sb.Append(selectionContent);
                            }
                        }
                    }
                    else if (selectedNodes.Count == 1)
                    {
                        HierarchyNode selectedNode = selectedNodes[0];
                        selectionContent = selectedNode.PrepareSelectedNodesForClipBoard();
                        if (selectionContent != null)
                        {
                            sb.Append(selectionContent);
                        }
                    }
                }

                // Add the project items first.
                IntPtr ptrToItems = this.PackageSelectionData(sb, false);
                if (ptrToItems == IntPtr.Zero)
                {
                    return(null);
                }

                FORMATETC fmt = DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSSTGPROJECTITEMS);
                dataObject = new DataObject();
                dataObject.SetData(fmt, ptrToItems);

                // Now add the project path that sourced data. We just write the project file path.
                IntPtr ptrToProjectPath = this.PackageSelectionData(new StringBuilder(this.GetMkDocument()), true);

                if (ptrToProjectPath != IntPtr.Zero)
                {
                    dataObject.SetData(DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSPROJECTCLIPDESCRIPTOR), ptrToProjectPath);
                }

                if (cutHighlightItems)
                {
                    bool first             = true;
                    IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);

                    foreach (HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
                    {
                        ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem));
                        first = false;
                    }
                }
            }
            catch (COMException e)
            {
                Trace.WriteLine("Exception : " + e.Message);

                dataObject = null;
            }

            return(dataObject);
        }
Пример #27
0
        public override void OnExecute(CommandEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            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.ItemSelectInFileExplorer:
                if (node == null || !node.Exists)
                {
                    return;
                }

                SelectInFileExplorer(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 && VSErr.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)), 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;
            }
        }
Пример #28
0
 internal SessionsNode(IVsUIHierarchyWindow window) {
     _window = window;
 }
Пример #29
0
        public override void OnExecute(CommandEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            // Cache items to avoid problems when selection changes by opening editor
            List <SvnItem> items = new List <SvnItem>(e.Selection.GetSelectedSvnItems(false));

            foreach (SvnItem item in items)
            {
                if (!item.Exists)
                {
                    continue;
                }

                bool selectInSolutionExplorer = false;

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

                        if (mapper.IsProjectFileOrSolution(item.FullPath))
                        {
                            selectInSolutionExplorer = true;
                            break;
                        }
                        if (item.IsDirectory)
                        {
                            goto case AnkhCommand.ItemOpenWindows;
                        }

                        VsShellUtilities.OpenDocument(e.Context, item.FullPath);
                        break;

                    case AnkhCommand.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 AnkhCommand.ItemOpenWindows:
                        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(item.FullPath);
                        psi.Verb = "open";
                        System.Diagnostics.Process.Start(psi);
                        break;
                    }
                }
                catch (IOException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (COMException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (InvalidOperationException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (System.ComponentModel.Win32Exception ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (selectInSolutionExplorer)
                {
                    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 && VSErr.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)), 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();
                            }
                        }
                    }
                }
            }
        }