public static Project GetActiveProject(IVsMonitorSelection vsMonitorSelection) { IntPtr ppHier = IntPtr.Zero; uint pitemid; IVsMultiItemSelect ppMIS; IntPtr ppSC = IntPtr.Zero; try { vsMonitorSelection.GetCurrentSelection(out ppHier, out pitemid, out ppMIS, out ppSC); if (ppHier == IntPtr.Zero) { return null; } // multiple items are selected. if (pitemid == (uint) VSConstants.VSITEMID.Selection) { return null; } IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(ppHier, typeof (IVsHierarchy)) as IVsHierarchy; if (hierarchy != null) { object project; if ( hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int) __VSHPROPID.VSHPROPID_ExtObject, out project) >= 0) { return (Project) project; } } return null; } finally { if (ppHier != IntPtr.Zero) { Marshal.Release(ppHier); } if (ppSC != IntPtr.Zero) { Marshal.Release(ppSC); } } }
public static string GetCurrentDocumentPath(this IServiceProvider serviceProvider) { IntPtr hierarchyPtr, selectionContainerPtr; uint projectItemId; IVsMultiItemSelect mis; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr); IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy; if (hierarchy != null) { object value; hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_ExtSelectedItem, out value); string path; hierarchy.GetCanonicalName(projectItemId, out path); return(path); } return(null); }
public static T GetSelectObject <T>() where T : class { IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = null; try { selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; } catch (Exception) { return(null); } if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } return(selectedObject as T); }
private bool CanGoToCode() { IntPtr hierarchyPtr, selectionContainerPtr; uint projectItemId; IVsMultiItemSelect mis; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr); IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy; if (hierarchy != null) { object value; hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_Name, out value); return(value != null && value.ToString().EndsWith(".html")); } else { return(false); } }
/// <summary> /// Gets the current selected IVsHierarchy. /// </summary> public static IVsHierarchy GetCurrentSelection(System.IServiceProvider provider, out uint pitemid) { Guard.ArgumentNotNull(provider, "provider"); IVsMonitorSelection pSelection = (IVsMonitorSelection)provider.GetService(typeof(SVsShellMonitorSelection)); IntPtr ptrHierchary = IntPtr.Zero; IVsMultiItemSelect ppMIS = null; IntPtr ppSC = IntPtr.Zero; pSelection.GetCurrentSelection(out ptrHierchary, out pitemid, out ppMIS, out ppSC); if (ptrHierchary != IntPtr.Zero) { return((IVsHierarchy)Marshal.GetObjectForIUnknown(ptrHierchary)); } else // There is not selection, so let's return the solution { IVsHierarchy solution = (IVsHierarchy)provider.GetService(typeof(SVsSolution)); pitemid = __VSITEMID.ROOT; return(solution); } }
private bool CanGoToView() { IntPtr hierarchyPtr, selectionContainerPtr; uint projectItemId; IVsMultiItemSelect mis; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr); IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy; if (hierarchy != null) { string path; hierarchy.GetCanonicalName(projectItemId, out path); return(path != null && IsCode(path) && GetViewPath(path) != null); } else { return(false); } }
public static string GetCurrentProject() { IntPtr hierarchyPtr, selectionContainerPtr; Object prjItemObject = null; IVsMultiItemSelect mis; uint prjItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPtr, out prjItemId, out mis, out selectionContainerPtr); if (hierarchyPtr == IntPtr.Zero) { return(null); } IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { try { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty(prjItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out prjItemObject)); } catch (Exception ex) { return(null); } } ProjectItem selectedPrjItem = prjItemObject as ProjectItem; if (selectedPrjItem != null && selectedPrjItem.ContainingProject != null) { return(selectedPrjItem.ContainingProject.Name); } return(null); }
public static IVsHierarchy GetSelectedHierarchy() { IntPtr ptr; IntPtr ptr2; uint num; IVsMultiItemSelect select; IVsHierarchy hierarchy = null; IVsMonitorSelection selection = Package.GetGlobalService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; if (selection.GetCurrentSelection(out ptr, out num, out select, out ptr2) == 0) { if (ptr != IntPtr.Zero) { hierarchy = Marshal.GetObjectForIUnknown(ptr) as IVsHierarchy; Marshal.Release(ptr); } } return(hierarchy); }
public Selection(IVsMonitorSelection monitorSelection) { if (monitorSelection == null) { throw new ArgumentNullException("monitorSelection"); } var ppMIS = default(IVsMultiItemSelect); ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out m_ppHier, out m_itemId, out ppMIS, out m_ppSC)); if (m_ppHier == IntPtr.Zero) { return; } if (m_itemId == (uint)VSConstants.VSITEMID.Selection) { return; } Hierarchy = (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(m_ppHier, typeof(IVsHierarchy)); }
/// <summary> /// Gets the path of currently selected item in Solution Explorer. /// </summary> private string GetPathOfSelectedItem() { IVsUIShellOpenDocument openDocument = Package.GetGlobalService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; IVsMultiItemSelect multiItemSelect = null; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainerPtr = IntPtr.Zero; int hr = VSConstants.S_OK; uint itemid = VSConstants.VSITEMID_NIL; hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr); IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; IVsUIHierarchy uiHierarchy = hierarchy as IVsUIHierarchy; // Get the file path string filePath = null; ((IVsProject)hierarchy).GetMkDocument(itemid, out filePath); return(filePath); }
private static bool GetSelectedFileDetails(OleMenuCommand menuCommand, out IVsHierarchy hierarchy, out uint itemID, out string fileName) { if (menuCommand != null) { IVsMonitorSelection monitorSelection = (IVsMonitorSelection)ServiceProvider.GlobalProvider.GetService(typeof(SVsShellMonitorSelection)); IntPtr ppHier; IVsMultiItemSelect ppMIS; IntPtr ppSC; monitorSelection.GetCurrentSelection(out ppHier, out itemID, out ppMIS, out ppSC); hierarchy = Marshal.GetTypedObjectForIUnknown(ppHier, typeof(IVsHierarchy)) as IVsHierarchy; // If new selection is a file we know how to display, then display it. if (VsHelper.TryGetFileName(hierarchy, itemID, out fileName)) { return(true); } } hierarchy = null; itemID = 0; fileName = null; return(false); }
/// <summary> /// Gets all of the currently selected items. /// </summary> /// <returns></returns> private VSITEMSELECTION?GetSelectedItem() { IVsMonitorSelection monitorSelection = GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainer = IntPtr.Zero; try { uint selectionItemId; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out selectionItemId, out multiItemSelect, out selectionContainer)); if (selectionItemId != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero) { IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (selectionItemId != VSConstants.VSITEMID_SELECTION) { // This is a single selection. Compare hirarchy with our hierarchy and get node from itemid return(new VSITEMSELECTION() { itemid = selectionItemId, pHier = hierarchy }); } } } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } return(null); }
/// <summary> /// Gets the properties of the currently selected projects necessary for reset. /// </summary> protected override bool GetProjectProperties( out ImmutableArray <string> references, out ImmutableArray <string> referenceSearchPaths, out ImmutableArray <string> sourceSearchPaths, out ImmutableArray <string> namespacesToImport, out string projectDirectory) { var hierarchyPointer = default(IntPtr); var selectionContainerPointer = default(IntPtr); references = ImmutableArray <string> .Empty; referenceSearchPaths = ImmutableArray <string> .Empty; sourceSearchPaths = ImmutableArray <string> .Empty; namespacesToImport = ImmutableArray <string> .Empty; projectDirectory = null; try { uint itemid; IVsMultiItemSelect multiItemSelectPointer; Marshal.ThrowExceptionForHR(_monitorSelection.GetCurrentSelection( out hierarchyPointer, out itemid, out multiItemSelectPointer, out selectionContainerPointer)); if (hierarchyPointer != IntPtr.Zero) { GetProjectProperties(hierarchyPointer, out references, out referenceSearchPaths, out sourceSearchPaths, out namespacesToImport, out projectDirectory); return(true); } } finally { SafeRelease(hierarchyPointer); SafeRelease(selectionContainerPointer); } return(false); }
private string GetClickedFolderNodePath() { ThreadHelper.ThrowIfNotOnUIThread(); IntPtr hierarchyPointer, selectionContainerPointer; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; selectedHierarchy.GetCanonicalName(projectItemId, out string folderPath); return(Path.GetDirectoryName(folderPath).Replace("//", "/")); }
private void Button_Click(object sender, RoutedEventArgs e) { IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } Project selectedProject = selectedObject as Project; string ProjectPath = System.IO.Path.GetDirectoryName(selectedProject.FullName); string ProjectName = selectedProject.Name; Logic.GetChanges(ProjectPath, TxtSavePath.Text, ProjectName, int.Parse(TxtDayCount.Text), ChkShowInExplorer.IsChecked.Value, ChkGetAll.IsChecked.Value, ChkMakeRar.IsChecked.Value, TxtExt.Text); Close(); }
public int GetCurrentSelection(out IntPtr ppHier, out uint pitemid, out IVsMultiItemSelect ppMIS, out IntPtr ppSC) { return(_selection.GetCurrentSelection(out ppHier, out pitemid, out ppMIS, out ppSC)); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { string message = "Refactoy concluido com sucesso !"; string title = "Refactory - Microserviço"; IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } EnvDTE.Project selectedProject = selectedObject as EnvDTE.Project; string projectPath = selectedProject.FullName; var classesEncontradas = GetAllProjectFiles(selectedProject.ProjectItems, ".cs"); var projectEvalution = new Microsoft.Build.Evaluation.Project(projectPath); if (!Directory.Exists(Path.Combine(selectedProject.Properties.Item("FullPath").Value.ToString(), "Service"))) { selectedProject.ProjectItems.AddFolder("Service"); projectEvalution.AddItem("Folder", Path.Combine(selectedProject.Properties.Item("FullPath").Value.ToString(), "Service")); } foreach (string classe in classesEncontradas) { var newClass = AnalisadorAST.Analisar(Arquivo.LerClasse(classe)); if (newClass != null) { Arquivo.CriarArquivo(newClass.Interface, selectedProject, projectEvalution, "I" + newClass.Name + ".cs"); Arquivo.CriarArquivo(newClass.Classe, selectedProject, projectEvalution, newClass.Name + ".cs"); } } //Show a message box to prove we were here VsShellUtilities.ShowMessageBox( this.ServiceProvider, message, title, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(DestinationType destination) { string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName); ProjectItems rootItems = null; switch (destination) { case DestinationType.Solution: { } break; case DestinationType.SolutionFolder: case DestinationType.Project: { // figure out if a project or project-folder was clicked try { IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } dynamic dyn = selectedObject; rootItems = (ProjectItems)(dyn.ProjectItems); } catch (Exception) { // what the heck was clicked ??? } } break; } string basePath; switch (destination) { default: case DestinationType.Solution: case DestinationType.SolutionFolder: { Solution2 sol2 = (Solution2)dte.Solution; basePath = Path.GetDirectoryName(sol2.FullName); } break; case DestinationType.Project: { basePath = Path.GetDirectoryName(rootItems.ContainingProject.FullName); } break; } try { DirectoryInfo folder = GetFolder(basePath, destination); if (folder == null) { return; } const string folderKindVirtual = @"{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}"; const string folderKindPhysical = @"{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"; string folderKind = folderKindVirtual; bool isSolutionFolder = false; switch (destination) { case DestinationType.Solution: { Solution2 solution = (Solution2)dte.Solution; rootItems = solution.AddSolutionFolder(folder.Name).ProjectItems; isSolutionFolder = true; } break; case DestinationType.SolutionFolder: { var solutionFolder = (SolutionFolder)((Project)rootItems.Parent).Object; rootItems = solutionFolder.AddSolutionFolder(folder.Name).ProjectItems; isSolutionFolder = true; } break; case DestinationType.Project: { if (rootItems != null) { try { // try virtual folder first (C/C++ projects) rootItems = rootItems.AddFolder(folder.Name, folderKind).ProjectItems; } catch (Exception) { // try physical folder (.net language projects) folderKind = folderKindPhysical; rootItems = rootItems.AddFolder(folder.Name, folderKind).ProjectItems; } } } break; } IncludeFiles(folder, rootItems, isSolutionFolder, folderKind, folder.Name); } catch (Exception ex) { dte.StatusBar.Text = $"Error while Creating Folders: {ex.Message}"; } }
/// <summary> /// Retrieves the selected hierarchy item in the given solution /// </summary> /// <param name="solution">Current solution</param> /// <returns>Selected hierarchy</returns> public static IVsHierarchy GetSelectedHierarchy(this IVsSolution solution, out uint itemId) { // Set default item id itemId = VSConstants.VSITEMID_NIL; // Check for solution is null or not! if (solution == null) { return(null); } // Create handles IVsMultiItemSelect multiItemSelect = null; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainerPtr = IntPtr.Zero; IVsHierarchy selectedHierarchy = null; Guid guidProjectID = Guid.Empty; // Get global service IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; // Check monitor selection is null or not! if (monitorSelection == null) { return(null); } try { // Retrieve selection int hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemId, out multiItemSelect, out selectionContainerPtr); // Check check check if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemId == VSConstants.VSITEMID_NIL || multiItemSelect != null || itemId == VSConstants.VSITEMID_ROOT) { return(null); } // Retrieve hierarchy if ((selectedHierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy) == null) { return(null); } if (ErrorHandler.Failed(solution.GetGuidOfProject(selectedHierarchy, out guidProjectID))) { return(null); // hierarchy is not a project inside the Solution if it does not have a ProjectID Guid } // if we got this far then there is a single project item selected return(selectedHierarchy); } finally { if (selectionContainerPtr != IntPtr.Zero) { Marshal.Release(selectionContainerPtr); } if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } } }
public static IVsHierarchy GetSelectedHierarchy(this IVsMonitorSelection monitorSelection, IUIThread uiThread) { var hierarchyPtr = IntPtr.Zero; var selectionContainer = IntPtr.Zero; return(uiThread.Invoke(() => { try { // Get the current project hierarchy, project item, and selection container for the current selection // If the selection spans multiple hierarchies, hierarchyPtr is Zero. // So fast path is for non-zero result (most common case of single active project/item). uint itemid; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer)); // There may be no selection at all. if (itemid == VSConstants.VSITEMID_NIL) { return null; } if (itemid == VSConstants.VSITEMID_ROOT) { // The root selection could be the solution itself, so no project is active. if (hierarchyPtr == IntPtr.Zero) { return null; } else { return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)); } } // We may have a single item selection, so we can safely pick its owning project/hierarchy. if (itemid != VSConstants.VSITEMID_SELECTION) { return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)); } // Otherwise, this is a multiple item selection within the same hierarchy, // we select he hierarchy. uint numberOfSelectedItems; int isSingleHierarchyInt; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt)); var isSingleHierarchy = (isSingleHierarchyInt != 0); if (isSingleHierarchy) { return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)); } return null; } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } })); }
/// <summary> /// Gets the list of directly selected VSITEMSELECTION objects /// </summary> /// <returns>A list of VSITEMSELECTION objects</returns> private IList <VSITEMSELECTION> GetSelectedNodes() { // Retrieve shell interface in order to get current selection IVsMonitorSelection monitorSelection = _sccProvider.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; Debug.Assert(monitorSelection != null, "Could not get the IVsMonitorSelection object from the services exposed by this project"); if (monitorSelection == null) { throw new InvalidOperationException(); } List <VSITEMSELECTION> selectedNodes = new List <VSITEMSELECTION>(); IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainer = IntPtr.Zero; try { // Get the current project hierarchy, project item, and selection container for the current selection // If the selection spans multiple hierachies, hierarchyPtr is Zero uint itemid; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer)); if (itemid != VSConstants.VSITEMID_SELECTION) { // We only care if there are nodes selected in the tree if (itemid != VSConstants.VSITEMID_NIL) { if (hierarchyPtr == IntPtr.Zero) { // Solution is selected VSITEMSELECTION vsItemSelection; vsItemSelection.pHier = null; vsItemSelection.itemid = itemid; selectedNodes.Add(vsItemSelection); } else { IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierarchyPtr); // Single item selection VSITEMSELECTION vsItemSelection; vsItemSelection.pHier = hierarchy; vsItemSelection.itemid = itemid; selectedNodes.Add(vsItemSelection); } } } else { if (multiItemSelect != null) { // This is a multiple item selection. //Get number of items selected and also determine if the items are located in more than one hierarchy uint numberOfSelectedItems; int isSingleHierarchyInt; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt)); bool isSingleHierarchy = (isSingleHierarchyInt != 0); // Now loop all selected items and add them to the list Debug.Assert(numberOfSelectedItems > 0, "Bad number of selected itemd"); if (numberOfSelectedItems > 0) { VSITEMSELECTION[] vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems]; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(0, numberOfSelectedItems, vsItemSelections)); foreach (VSITEMSELECTION vsItemSelection in vsItemSelections) { selectedNodes.Add(vsItemSelection); } } } } } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } return(selectedNodes); }
/// <summary> /// Called when the Generate Migrations command is run /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> private void MigrationsCallback(object sender, EventArgs e) { IntPtr hierarchyPtr, selectionContainerPtr; uint projectItemId; IVsMultiItemSelect mis; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)GetGlobalService(typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr); IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy; if (hierarchy == null) { FireError("F**k knows why but it is broken, sorry"); return; } object projObj; hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out projObj); ProjectItem projItem = projObj as ProjectItem; if (projItem == null) { FireError("The item you have selected is not playing nicely. Apologies"); return; } var project = projItem.ContainingProject; var migrations = new List <Migration>(); var allClasses = GetProjectItems(project.ProjectItems).Where(v => v.Name.Contains(".cs")); // check for .cs extension on each, foreach (var c in allClasses) { var eles = c.FileCodeModel; if (eles == null) { continue; } foreach (var ele in eles.CodeElements) { if (ele is EnvDTE.CodeNamespace) { var ns = ele as EnvDTE.CodeNamespace; // run through classes foreach (var property in ns.Members) { var member = property as CodeType; if (member == null) { continue; } // check all classes they derive from to see if any of them are migration classes, add them if so migrations.AddRange(from object b in member.Bases select b as CodeClass into bClass where bClass != null && bClass.Name == "DataMigrationImpl" select new Migration(member)); } } } } var model = projItem.FileCodeModel; if (model == null) { FireError("This class you have selected is weird and broken. Choose another one"); return; } var elements = model.CodeElements; var classes = new List <Model>(); // run through elements (they are done in a hierachy, so first we have using statements and the namespace) to find namespace foreach (var ele in elements) { if (ele is EnvDTE.CodeNamespace) { var ns = ele as EnvDTE.CodeNamespace; // run through classes foreach (var c in ns.Members) { var member = c as CodeType; if (member == null) { continue; } classes.Add(new Model() { Class = member, Name = member.Name }); } } } if (!classes.Any()) { FireError("No classes in the selected file!"); return; } var vm = new MigrationsViewModel(migrations, classes); var window = new MigrationsWindow(vm); var success = window.ShowDialog(); if (!success.GetValueOrDefault()) { return; } CodeType selectedClass = vm.SelectedClass.Class; if (selectedClass == null) { FireError("No class to generate migrations from!"); return; } // name of class var modelName = selectedClass.Name; // get code class var cc = selectedClass as CodeClass; // get all members of the class var members = cc.Members; bool contentPartRecord = false; foreach (var d in cc.Bases) { var dClass = d as CodeClass; if (dClass != null && dClass.Name == "ContentPartRecord") { contentPartRecord = true; } } var props = new List <MigrationItem>(); //iterate through to find properties foreach (var member in members) { var prop = member as CodeProperty; if (prop == null) { continue; } if (prop.Access != vsCMAccess.vsCMAccessPublic) { continue; } var type = prop.Type; var name = prop.Name; var fullName = type.AsFullName; var nullable = fullName.Contains(".Nullable<"); var sType = type.AsString.Replace("?", ""); var sName = name; // if model, add _Id for nhibernate if (fullName.Contains(".Models.") || fullName.Contains(".Records.")) { sName += "_Id"; sType = "int"; } var mi = new MigrationItem() { Name = name, SuggestedName = sName, Type = fullName, SuggestedType = sType, Nullable = nullable, Create = true, }; props.Add(mi); } var createMigrationFile = !String.IsNullOrEmpty(vm.NewMigration); if (!createMigrationFile) { if (vm.SelectedMigration == null) { FireError("Select a migration or choose a new one!"); return; } var mig = vm.SelectedMigration.CodeType; string path = (string)mig.ProjectItem.Properties.Item("FullPath").Value; string text = File.ReadAllText(path); var noTimesCreated = Regex.Matches(text, @"SchemaBuilder.Create\(""" + modelName + @""",").Count; var noTimesDropped = Regex.Matches(text, @"SchemaBuilder.DropTable\(""" + modelName + @"""\)").Count; bool created = noTimesCreated > noTimesDropped; if (noTimesCreated == 1 && noTimesDropped == 0) { foreach (var p in props.Where(p => text.Contains(p.Name))) { p.Create = false; } } if (created) { foreach (var p in props) { var name = p.Name; var noDrops = Regex.Matches(text, @".DropColumn\(""" + name).Count; var noOccurences = Regex.Matches(text, name).Count; if ((noOccurences - noDrops) > noDrops) { p.Create = false; } } } } // if a collection ignore foreach (var p in props) { if (p.Type.Contains("System.Collection")) { p.Create = false; } } var bmvm = new BuildMigrationsViewModel(props); var bmWindow = new BuildMigrationsWindow(bmvm); var bmSuccess = bmWindow.ShowDialog(); if (!bmSuccess.GetValueOrDefault()) { return; } var sb = new StringBuilder(); var createTable = "SchemaBuilder.CreateTable(\"" + modelName + "\", t => t"; sb.AppendLine(createTable); if (contentPartRecord) { sb.AppendLine("\t.ContentPartRecord()"); } foreach (var p in bmvm.Migrations.Where(z => z.Create)) { sb.AppendLine("\t" + ParseMigrationItem(p)); } sb.AppendLine(");"); var editViewModel = new EditMigrationsViewModel() { Migrations = sb.ToString() }; var editWindow = new EditMigrationsWindow(editViewModel); var emSuccess = editWindow.ShowDialog(); if (!emSuccess.GetValueOrDefault()) { return; } var migrationsCode = new StringBuilder(); using (StringReader reader = new StringReader(editViewModel.Migrations)) { string line; while ((line = reader.ReadLine()) != null) { migrationsCode.AppendLine(line.Insert(0, "\t\t\t")); } } if (!createMigrationFile) { EditMigrations(vm.SelectedMigration.CodeType, migrationsCode.ToString()); } else { var templates = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "OrchardTemplates"); var newMigration = project.ProjectItems.AddFromFileCopy(templates + "\\Migrationsxxx.cs"); Insert(newMigration.Properties.Item("FullPath").Value.ToString(), new[] { new KeyValuePair <string, string>("$module$", project.Name), new KeyValuePair <string, string>("$migrationName$", vm.NewMigration), new KeyValuePair <string, string>("$code$", migrationsCode.ToString()) }); var cs = vm.NewMigration.EndsWith(".cs") ? "" : ".cs"; newMigration.Name = vm.NewMigration + cs; } }
/// <summary> /// Gets all of the currently selected items. /// </summary> /// <returns></returns> private IEnumerable <VSITEMSELECTION> GetSelectedItems() { IVsMonitorSelection monitorSelection = _package.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainer = IntPtr.Zero; try { uint selectionItemId; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out selectionItemId, out multiItemSelect, out selectionContainer)); if (selectionItemId != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero) { IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (selectionItemId != VSConstants.VSITEMID_SELECTION) { // This is a single selection. Compare hirarchy with our hierarchy and get node from itemid if (Utilities.IsSameComObject(this, hierarchy)) { yield return(new VSITEMSELECTION() { itemid = selectionItemId, pHier = hierarchy }); } } else if (multiItemSelect != null) { // This is a multiple item selection. // Get number of items selected and also determine if the items are located in more than one hierarchy uint numberOfSelectedItems; int isSingleHierarchyInt; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt)); bool isSingleHierarchy = (isSingleHierarchyInt != 0); // Now loop all selected items and add to the list only those that are selected within this hierarchy if (!isSingleHierarchy || (isSingleHierarchy && Utilities.IsSameComObject(this, hierarchy))) { Debug.Assert(numberOfSelectedItems > 0, "Bad number of selected itemd"); VSITEMSELECTION[] vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems]; uint flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections)); foreach (VSITEMSELECTION vsItemSelection in vsItemSelections) { yield return(new VSITEMSELECTION() { itemid = vsItemSelection.itemid, pHier = hierarchy }); } } } } } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } }
private void OnBeforeQueryStatus(object sender, EventArgs e) { projects.Clear(); var cmd = sender as OleMenuCommand; if (cmd == null) { return; } IVsMonitorSelection monitorSelection = sp.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; if (monitorSelection == null) { return; } IntPtr hier = IntPtr.Zero; UInt32 itemid; IVsMultiItemSelect multiitem = null; IntPtr container = IntPtr.Zero; try { monitorSelection.GetCurrentSelection(out hier, out itemid, out multiitem, out container); /* Bail out if nothing is selected */ if (itemid != VSConstants.VSITEMID_SELECTION && itemid != VSConstants.VSITEMID_NIL) { if (hier == IntPtr.Zero) { /* FIXME: parse the whole solution */ } else { object project = null; IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hier); hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out project); projects.Add(project as Project); } } } finally { if (hier != IntPtr.Zero) { Marshal.Release(hier); } if (container != IntPtr.Zero) { Marshal.Release(container); } } // If there are .l or .y files in this project, display the context menu Visible = false; foreach (Project project in projects) { foreach (ProjectItem item in ParseProjectItems(project)) { if (item.Name.EndsWith("-scanner.l", StringComparison.CurrentCultureIgnoreCase) || item.Name.EndsWith("-parser.y", StringComparison.CurrentCultureIgnoreCase)) { Visible = true; } } } }
/// <summary> /// Verifies if a single object is selected /// </summary> /// <param name="hierarchy">Current selected project hierarchy</param> /// <param name="itemid">ID of the selected item</param> /// <returns>True if a single item is selected</returns> public static bool IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out uint itemid) { hierarchy = null; itemid = VSConstants.VSITEMID_NIL; int hr = VSConstants.S_OK; IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; IVsSolution solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution; if (monitorSelection == null || solution == null) { return(false); } IVsMultiItemSelect multiItemSelect = null; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainerPtr = IntPtr.Zero; try { hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr); if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL) { // there is no selection return(false); } if (multiItemSelect != null) { // multiple items are selected return(false); } if (itemid == VSConstants.VSITEMID_ROOT) { // there is a hierarchy root node selected, thus it is not a single item inside a project return(false); } hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (hierarchy == null) { return(false); } Guid guidProjectID = Guid.Empty; if (ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out guidProjectID))) { return(false); // hierarchy is not a project inside the Solution if it does not have a ProjectID Guid } // if we got this far then there is a single project item selected return(true); } finally { if (selectionContainerPtr != IntPtr.Zero) { Marshal.Release(selectionContainerPtr); } if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } Project selectedProject = selectedObject as Project; string projectPath = selectedProject.FullName; var batPath = Path.Combine(Path.GetDirectoryName(projectPath), "scaffold.bat"); if (!File.Exists(batPath)) { VsShellUtilities.ShowMessageBox( this.package, "找不到 scaffold.bat 檔案", "找不到批次檔", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); return; } var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = batPath, WorkingDirectory = Path.GetDirectoryName(projectPath) }); proc.WaitForExit(); if (proc.ExitCode == 0) { VsShellUtilities.ShowMessageBox( this.package, "更新完成", "EFCore Models 更新完成", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); return; } else { VsShellUtilities.ShowMessageBox( this.package, "更新失敗,請檢查批次檔內的資料庫連線字串", "EFCore Models 更新失敗", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); return; } }
public Project GetSelectedProject() { IntPtr hierarchyPointer = IntPtr.Zero; IntPtr selectionContainerPointer = IntPtr.Zero; try { Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Microsoft.VisualStudio.Shell.Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { if (ErrorHandler.Failed(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject))) { return(null); } } Project project = selectedObject as Project; var vsproject = project?.Object as VSProject; if (vsproject != null) { //If we are an assembly, and its named WPILib, enable the deploy foreach (Reference reference in vsproject.References) { string name = reference.Name; if (name.Contains("WPILib")) { return(project); } /* * if (reference.SourceProject == null) * { * * } */ } } return(null); } finally { if (selectionContainerPointer != IntPtr.Zero) { Marshal.Release(selectionContainerPointer); } if (hierarchyPointer != IntPtr.Zero) { Marshal.Release(hierarchyPointer); } } }
public static IEnumerable <Tuple <IVsHierarchy, uint> > GetSelection(this IVsMonitorSelection monitorSelection, IUIThread uiThread, IVsHierarchy solution) { var hierarchyPtr = IntPtr.Zero; var selectionContainer = IntPtr.Zero; return(uiThread.Invoke(() => { try { // Get the current project hierarchy, project item, and selection container for the current selection // If the selection spans multiple hierarchies, hierarchyPtr is Zero uint itemid; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer)); if (itemid == VSConstants.VSITEMID_NIL) { return Enumerable.Empty <Tuple <IVsHierarchy, uint> >(); } if (itemid == VSConstants.VSITEMID_ROOT) { if (hierarchyPtr == IntPtr.Zero) { return new[] { Tuple.Create(solution, VSConstants.VSITEMID_ROOT) } } ; else { return new[] { Tuple.Create( (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)), VSConstants.VSITEMID_ROOT) } }; } if (itemid != VSConstants.VSITEMID_SELECTION) { return new[] { Tuple.Create( (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)), itemid) } } ; // This is a multiple item selection. uint numberOfSelectedItems; int isSingleHierarchyInt; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt)); var isSingleHierarchy = (isSingleHierarchyInt != 0); var vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems]; var flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections)); return vsItemSelections.Where(sel => sel.pHier != null) // NOTE: we can return lazy results here, since // the GetSelectedItems has already returned in the UI thread // the array of results. We're just delaying the creation of the tuples // in case they aren't all needed. .Select(sel => Tuple.Create(sel.pHier, sel.itemid)); } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } })); }