Skip to content

Instantly share code, notes, and snippets.

@WaltRitscher
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WaltRitscher/25f2155e32242388887e to your computer and use it in GitHub Desktop.
Save WaltRitscher/25f2155e32242388887e to your computer and use it in GitHub Desktop.
Visual Studio 2010 Macros (Code Formatting)
Option Strict On
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.ComponentModel.Design
Imports EnvDTE90
Imports System.Windows.Forms
Imports System.Linq
Imports System.IO
Imports System.Collections
' not happy with approach taken in some of these macros
' but calling macros in VS IDE
' forces tradeoffs and poor coding model.
' rewrite these as VS2010 addin when available
Public Module FormattingMacros
Private _projectsList As Generic.List(Of Project) = New Collections.Generic.List(Of Project)
Private _flattenedProjItems As Generic.List(Of ProjectItem) = New Collections.Generic.List(Of ProjectItem)
' this method can only be used in VS 2010
' <System.Runtime.CompilerServices.Extension()> _
'Public Function EndsWith(ByVal sourceString As String, ByVal stringsToEvaluate As Generic.IEnumerable(Of String)) As Boolean
' Return stringsToEvaluate.Any(Function(item) sourceString.EndsWith(item, True, Nothing))
' End Function
' this method can be used by VS 2008
Public Function EndsWith(ByVal sourceString As String, ByVal stringsToEvaluate As Generic.IEnumerable(Of String)) As Boolean
For Each item In stringsToEvaluate
If sourceString.ToLower().EndsWith(item.ToLower()) Then
Return True
End If
Next
Return False
End Function
Public Sub SolutionExplorer_FormatSelectedItems()
DTE.SuppressUI = True
Dim uih As UIHierarchy = DirectCast(DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Object, UIHierarchy)
Dim selectedItems As New Collections.Generic.List(Of UIHierarchyItem)
Dim selectedProjectItems As New Collections.Generic.List(Of ProjectItem)
' Get the selected items from the Solution Explorer
Dim rawItems As System.Array = CType(uih.SelectedItems, System.Array)
' place them in our own typed lists
For Each item As Object In rawItems
Dim uiItem As UIHierarchyItem = CType(item, UIHierarchyItem)
selectedItems.Add(uiItem)
selectedProjectItems.Add(DTE.Solution.FindProjectItem(uiItem.Name))
Next
For Each projectItem As ProjectItem In selectedProjectItems
FormatOpenWindow(projectItem)
Next
'DTE.Documents.CloseAll(vsSaveChanges.vsSaveChangesYes)
DTE.SuppressUI = False
End Sub
Private Sub FormatOpenWindow(ByVal item As ProjectItem)
' get the first file affiliated with our project item
' warning - this may not work with multi- file items like winforms or Asp.Net forms
Dim win As Window = DTE.ItemOperations.OpenFile(item.FileNames(1))
win.Activate()
' we need to have a TextDocument to manipulate the contents
Dim td As TextDocument
td = DirectCast(win.Document.Object("TextDocument"), EnvDTE.TextDocument)
Try
If td IsNot Nothing Then
' do the formatting
' td.StartPoint.CreateEditPoint.SmartFormat(td.EndPoint.CreateEditPoint)
' td.Selection.SelectAll()
' EnvDTE.EditPoint.SmartFormat(TextPoint)
'td.StartPoint.CreateEditPoint.SmartFormat(td.EndPoint)
'element.GetStartPoint().CreateEditPoint().SmartFormat(element.GetEndPoint())
Dim endPoint As EditPoint
Dim startPoint As EditPoint
endPoint = td.EndPoint.CreateEditPoint
startPoint = td.StartPoint.CreateEditPoint
startPoint.StartOfDocument()
endPoint.EndOfDocument()
startPoint.SmartFormat(endPoint)
' Dim com As Command = DTE.Commands.Item("Build.CleanSolution", -1)
' Dim com As Command = DTE.Commands.Item("Edit.FormatDocument", -1)
' Threading.Thread.Sleep(300)
DTE.ExecuteCommand("Edit.FormatDocument", String.Empty)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Public Sub CleanProjects()
' Opens all files in project
' that are considered 'Common WPF files'
' then runs the cleanup method
' then collapses all nodes in Solution Explorer
DTE.SuppressUI = True
Dim proj As Project
Try
OpenFiles_CommonWpf()
Catch ex As Exception
Debug.Print(ex.Message)
End Try
Try
CleanAllOpenWindows()
SolutionExplorer_CollapseAllNodes()
Catch ex As Exception
Debug.Print(ex.Message)
End Try
DTE.Documents.CloseAll(vsSaveChanges.vsSaveChangesYes)
DTE.SuppressUI = False
End Sub
Public Sub OpenFiles_Xaml()
FlattenList()
Dim include As New Generic.List(Of String)
Dim exclude As New Generic.List(Of String)
include.Add(".xaml")
OpenWindows(_flattenedProjItems, include, exclude)
End Sub
Public Sub OpenFiles_VB()
FlattenList()
Dim include As New Generic.List(Of String)
Dim exclude As New Generic.List(Of String)
include.Add(".vb")
OpenWindows(_flattenedProjItems, include, exclude)
End Sub
Public Sub OpenFiles_CS()
' http://www.mztools.com/articles/2006/MZ2006004.aspx
FlattenList()
Dim include As New Generic.List(Of String)
Dim exclude As New Generic.List(Of String)
include.Add(".cs")
OpenWindows(_flattenedProjItems, include, exclude)
End Sub
Public Sub OpenFiles_WithPrompt()
Dim ext As String = InputBox("Enter an extension for the file type to open. (example: .cs)", _
"What Extension...", _
".xaml")
FlattenList()
Dim include As New Generic.List(Of String)
Dim exclude As New Generic.List(Of String)
include.Add(ext)
OpenWindows(_flattenedProjItems, include, exclude)
End Sub
Public Sub OpenFiles_CommonWpf()
FlattenList()
Dim include As New Generic.List(Of String)
Dim exclude As New Generic.List(Of String)
include.Add(".cs")
include.Add(".xaml")
exclude.Add(".designer.cs")
OpenWindows(_flattenedProjItems, include, exclude)
End Sub
Private Sub FlattenList()
' entry point for the flatten file procedure
_flattenedProjItems = New Generic.List(Of ProjectItem)
For Each proj In GetAllProjects()
FillFlattenedFileList(proj.ProjectItems)
Next
End Sub
Private Sub FillFlattenedFileList(ByVal projItems As ProjectItems)
' walk the solution explorer tree
' load all nodes in a flat list
For Each candidate As ProjectItem In projItems
If Path.HasExtension(candidate.Name) Then
_flattenedProjItems.Add(candidate)
End If
If candidate.ProjectItems.Count > 0 Then
FillFlattenedFileList(candidate.ProjectItems)
End If
Next
End Sub
Private Sub OpenWindows(ByVal projItems As Collections.Generic.List(Of ProjectItem), _
ByVal includeExtensions As Generic.List(Of String), _
ByVal excludeExtensions As Generic.List(Of String))
' Opens all windows by lookin at file extensions
' includeExtensions: Which extensions should be opened (Example, .xaml, .vb)
' excludeExtensions: Which extension to exclude. (Example .designer.cs)
' the exclude list is handy when you don't want to open the VS auto generated files
' note: do not include wildcards (example *.txt)
For Each candidate As ProjectItem In projItems
If candidate.IsOpen(ViewKind:=Constants.vsViewKindAny) Then
Continue For
End If
If EndsWith(candidate.Name, excludeExtensions) Then
Continue For
End If
If EndsWith(candidate.Name, includeExtensions) Then
Dim editWindow As Window = candidate.Open(Constants.vsViewKindTextView)
editWindow.Activate()
End If
Next
End Sub
Public Sub CleanAllOpenWindows()
Try
For Each win As Window In DTE.Windows
win.Activate()
If win.Document Is Nothing Then
Continue For
End If
win.Document.Activate()
'CleanTemp(win.Document)
CleanCurrentWindow()
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
'Private Sub CleanTemp(ByVal doc As Document)
' doc.Activate()
' Dim com As Command = DTE.Commands.Item("Edit.FormatDocument")
' Dim textDoc As TextDocument
' Console.WriteLine(doc.Name)
' Try
' If TypeOf doc.Object Is TextDocument Then
' textDoc = DirectCast(doc.Object, TextDocument)
' textDoc.StartPoint.CreateEditPoint.SmartFormat(textDoc.EndPoint)
' RemoveAdjacentBlankLines()
' End If
' Catch ex As Exception
' Console.WriteLine(ex.Message)
' End Try
'End Sub
Public Sub CleanCurrentWindow()
' clean the active doc by
' removing blank lines
' calling the format document command
' calling the remove and sort usings command
Dim textDoc As TextDocument
Dim com As Command = DTE.Commands.Item("Edit.FormatDocument")
Dim win As Window = DTE.ActiveWindow
Dim doc As Document = win.Document
If doc Is Nothing Then
doc = DTE.ActiveDocument
End If
If TypeOf doc.Object Is TextDocument Then
textDoc = DirectCast(doc.Object, TextDocument)
textDoc.StartPoint.CreateEditPoint.SmartFormat(textDoc.EndPoint)
End If
If com.IsAvailable Then
DTE.ExecuteCommand("Edit.FormatDocument")
Else
Dim sk As SendKeys
sk.SendWait("^K^D")
End If
com = DTE.Commands.Item("EditorContextMenus.CodeWindow.OrganizeUsings.RemoveAndSort")
If com.IsAvailable Then
DTE.ExecuteCommand("EditorContextMenus.CodeWindow.OrganizeUsings.RemoveAndSort")
End If
RemoveAdjacentBlankLines()
End Sub
Private Function GetAllProjects() As Collections.Generic.List(Of Project)
' avoids the Solution Folders
Dim proj As EnvDTE.Project
_projectsList = New Collections.Generic.List(Of Project)
Try
If Not DTE.Solution.IsOpen Then
MessageBox.Show("Please load or create a solution")
Else
For Each proj In DTE.Solution.Projects
NavigateProject(proj)
Next
End If
Catch e As System.Exception
MessageBox.Show(e.ToString)
End Try
Return _projectsList
End Function
Private Sub NavigateProject(ByVal proj As Project)
Dim itemParent As ProjectItem
If proj.Kind <> "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}" Then
_projectsList.Add(proj)
End If
NavigateProjectItems(proj.ProjectItems)
End Sub
Private Sub NavigateProjectItems(ByVal projItems As ProjectItems)
Dim item As EnvDTE.ProjectItem
If (projItems IsNot Nothing) Then
For Each item In projItems
If (item.SubProject IsNot Nothing) Then
' We navigate recursively because it can be:
' - An Enterprise project in Visual Studio .NET 2002/2003
' - A solution folder in VS 2005
NavigateProject(item.SubProject)
Else
' We navigate recursively because it can be:
' - An folder inside a project
' - A project item with nested project items (code-behind files, etc.)
NavigateProjectItems(item.ProjectItems)
End If
Next
End If
End Sub
Sub SolutionExplorer_CollapseAllNodes()
' Get the the Solution Explorer tree
Dim solutionExplorer As UIHierarchy
solutionExplorer = DirectCast(DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object, UIHierarchy)
' Check if there is any open solution
If (solutionExplorer.UIHierarchyItems.Count = 0) Then
' MsgBox("Nothing to collapse. You must have an open solution.")
Return
End If
' Get the top node (the name of the solution)
Dim solutionRootNode As UIHierarchyItem
solutionRootNode = solutionExplorer.UIHierarchyItems.Item(1)
solutionRootNode.DTE.SuppressUI = True
' Collapse each project node
Dim node As UIHierarchyItem
For Each node In solutionRootNode.UIHierarchyItems
'UIHItem.UIHierarchyItems.Expanded = False
If node.UIHierarchyItems.Expanded Then
CollapseChildrenNodes(node)
End If
Next
' Select the solution node, or else when you click
' on the solution window
' scrollbar, it will synchronize the open document
' with the tree and pop
' out the corresponding node which is probably not what you want.
solutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
solutionRootNode.DTE.SuppressUI = False
End Sub
Private Sub CollapseChildrenNodes(ByVal parentNode As UIHierarchyItem)
' UIHierarchyItems: Represents all childrenNodes in the tree view.
For Each childNode As UIHierarchyItem In parentNode.UIHierarchyItems
If childNode.UIHierarchyItems.Expanded AndAlso childNode.UIHierarchyItems.Count > 0 Then
CollapseChildrenNodes(childNode)
End If
Next
parentNode.UIHierarchyItems.Expanded = False
End Sub
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment