Introduction
I find this useful and couldn't find anything like it before I wrote it, hence this article.
This is a simple little macro I came up with to alleviate the tedium of reversing assignments in source code. This is something I come across quite frequently when working with business objects and in ASP.NET forms where you initially set a series of objects with a value, then later want to reverse the assignment.
For example, you might want to convert this...
TextBox.Text=myobject.name;
... to this:
myobject.name=TextBox.Text;
Multiply that by dozens of assignments and it's quite tedious to reverse all that original code you wrote. Since this is very simple, I've just included it here in the article content. You can copy and paste it into your own macro in Visual Studio.
Note that it appends each line of code with a semicolon for C#, but you could easily modify it to not do that for VB or whatever you happen to be editing.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Text
Imports System.Text.RegularExpressions
Public Module JohnUtils
Private Function GetCurrentlySelectedText() As String
If Not DTE.ActiveDocument Is Nothing Then
Dim txt As TextSelection
txt = CType(DTE.ActiveDocument.Selection, TextSelection)
Return txt.Text
Else
Return String.Empty
End If
End Function
Sub SwapAssignmentRegion()
Dim line, originalCode As String
originalCode = GetCurrentlySelectedText()
If Not originalCode = String.Empty Then
Dim leftside As String
Dim rightside As String
Dim output As New System.Text.StringBuilder
Dim lines() As String
lines = Split(originalCode, vbLf)
Dim r As Regex
r = New Regex( _
"\s*(?<leftside>\S*)" & _
"\s*(=)\s*(?<rightside>\S*)", _
RegexOptions.IgnoreCase Or _
RegexOptions.ExplicitCapture)
For Each line In lines
line = line.Trim
If Not line = String.Empty Then
Dim mtch As Match
mtch = r.Match(line)
If mtch.Success Then
leftside = _
mtch.Groups("leftside").Value.Trim
rightside = _
mtch.Groups("rightside").Value.Trim.Replace(";", "")
output.AppendFormat( _
"{0}{1} = {2};", _
vbCrLf, rightside, _
leftside)
End If
End If
Next
DTE.UndoContext.Open("SwapAssignmentRegion")
Dim txt As TextSelection
txt = CType(DTE.ActiveDocument.Selection, TextSelection)
txt.Insert(vbCrLf + output.ToString, _
vsInsertFlags.vsInsertFlagsInsertAtEnd _
Or vsInsertFlags.vsInsertFlagsContainNewText)
txt.SmartFormat()
DTE.UndoContext.Close()
End If
End Sub
End Module
History
- 20th September, 2006: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.