Extending Intellisense: Namespace lookup with a macro (bis)
Thanks to a tip of Yves Hanoulle, there is now one single function that adds the using/Imports directive for both VB.NET and C#.
The macro works great if you assign a shortcut key to it, you can do that like this:
- Enter or copy-and-paste the macro code in the Macro Editor of Visual Studio.
- Choose in the Tools menu the Customize menu item.
- Press the Keyboard button (below right).
- In the list of the commands, find Macros.MyMacros.TypeFinder.AddDirective, and select it.
- In the textbox "Press shortcut key(s)", press the key combination you want to use. (I use Ctrl+`)
- Change the "Use new shortcut in:" value to "Text Editor"
- Press the Assign button.
Imports EnvDTE
Imports System.Diagnostics
Imports System
Public Module TypeFinder
Private Function SearchTypeInAssembly(ByVal typename As String _
, ByVal ass As Reflection.Assembly)
DTE.StatusBar.Text = "Searching for '" & typename & "' " & _
ass.GetName.Name & "..."
Dim t As Type
For Each t In ass.GetTypes
If t.Name.ToLower = typename Then
Return t
End If
Next
End Function
Private Function SearchType(ByVal typename As String) As Type
typename = typename.ToLower
Dim projs As System.Array = DTE.ActiveSolutionProjects
Dim ass As Reflection.Assembly = _
Reflection.Assembly.LoadWithPartialName("mscorlib")
Dim t As Type = SearchTypeInAssembly(typename, ass)
If Not t Is Nothing Then Return t
Dim proj As Project
For Each proj In projs
Dim o As VSLangProj.VSProject = proj.Object
Dim ref As VSLangProj.Reference
For Each ref In o.References
ass = Reflection.Assembly.LoadFile(ref.Path)
t = SearchTypeInAssembly(typename, ass)
If Not t Is Nothing Then Return t
Next
Next
DTE.StatusBar.Text = "Could not find type '" & typename & _
"' in the referenced libraries. Make sure your cursor " & _
"is right behind the text (without selection)!"
DTE.StatusBar.Highlight(True)
Return Nothing
End Function
Public Sub AddNamespace()
Dim text As TextSelection = DTE.ActiveDocument.Selection
text.WordLeft(True)
Dim t As Type = SearchType(text.Text)
If Not t Is Nothing Then
text.Text = t.FullName
text.EndOfLine()
DTE.StatusBar.Text = "Ready"
End If
End Sub
Public Sub AddDirective()
Dim text As TextSelection = DTE.ActiveDocument.Selection
text.WordLeft(True)
Dim t As Type = SearchType(text.Text)
If Not t Is Nothing Then
Dim keyword, suffix As String
Dim line As Integer = text.AnchorPoint.Line
text.Text = t.Name
text.StartOfDocument()
Select Case DTE.ActiveDocument.Language
Case "CSharp"
keyword = "using"
suffix = ";"
Case "Basic"
keyword = "Imports"
suffix = String.Empty
Case Else
Throw New System.Exception("Invalid Language: " & _
DTE.ActiveDocument.Language)
End Select
text.Insert(keyword & " " & t.Namespace & suffix & vbCrLf)
text.MoveToLineAndOffset(line + 1, 1)
text.EndOfLine()
DTE.StatusBar.Text = "'" & keyword & " " & t.Namespace & _
suffix & "' added to the document."
DTE.StatusBar.Highlight(True)
End If
End Sub
End Module