views:

214

answers:

1

I have a decent sized set of data that needs to be stored in an active record. In order to prepopulate the form fields on the page, I have already written the following code:

Device device = new Device(DeviceID); // device is simply the active record

txtDeviceName.Text = device.Name;
txtNotes.Text = device.Notes;
txtHostName.Text = device.Hostname;
txtAssetTag.Text = device.AssetTag;
txtSerialNumber.Text = device.SerialNumber;
// snip... the list goes on!

Is there some sort of the method (built-in functionality, macro, etc.) that I could use to swap each side of the expression such that the data is saved into the active record as opposed to read from it in order to perform a database insert? For example, after highlighting the above code and running the macro, it would become:

device.DeviceName = txtDeviceName.Text;
device.Notes = txtNotes.Text;
device.Hostname = txtHostName.Text;
device.AssetTag = txtAssetTag.Text;
device.SerialNumber = txtSerialNumber.Text;
// snip again...

Since the number of columns in the database that this active record encapsulates is rather large, it seems like most of this typing could be avoided with a simple automated process.

Obviously this wouldn't work 100% because sometimes there would have to be type conversions (e.g. int to string) but for the most part I think this would save a lot of time.

+5  A: 

Here is a macro that will do it:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Public Module Helpers
    Sub SwapAssignment()
        If (Not IsNothing(DTE.ActiveDocument)) Then
            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
            selection.Text = Regex.Replace(selection.Text, "([^\s]*)\s*=\s*([^\s]*);", "$2 = $1;")
        End If
    End Sub
End Module

Basically it takes the selected text (either one line or as many lines as you select) and uses a regular expression to swap the values. Not pretty but then macros never are.

Andrew Hare
Neat! Is there a way to perform it on the entire block of text as opposed to just one line?
John Rasch
It will work for as many lines of text as you select.
Andrew Hare
Odd, it only works for the 1st line when I select several at once. Are you using VS2008?
John Rasch
Ah - my mistake! I have fixed it now.
Andrew Hare
Please note the last fix that only requires a single cast.
Andrew Hare