Search code examples
asp.netvisual-studiostringadd-invisual-studio-macros

VS Macro/Add-in to convert string concatenations to string.format style


I have project in development where string operations like "Hi " + variable + ", welcome to Project" are used at many places (given example is very minor one).

One of the requirement is to convert it to string.format style.

It is very long and tedious job, where I would not like to break earlier working code due to any human error might happen while converting it.

I would like to if any Macro or VS command which I can create to handle it. Just like we mark block of code and do Extract function in Re-factor options.


Solution

  • I felt the code was a little long to post here, but I posted an answer at my blog: http://www.brianschmitt.com/2010/08/converting-concatenated-string-into.html

    -- EDIT -- Per comment here is the relevant Macro - not sure why you cannot access...

    Public Sub ConvertToStringFormat()
        DTE.UndoContext.Open("ConvertToStringFormat")
        Dim textSelection As TextSelection = DTE.ActiveDocument.Selection
        Dim output As String = "string.Format(""{0}"", {1})"
        Dim delimt As String = ", "
        Dim fmtdTostring As String = ".tostring("""
    
        Dim txtSelection As String() = System.Text.RegularExpressions.Regex.Split(textSelection.Text.Trim, "\+\s_[+\n\r\t]|&\s_[+\n\r\t]|\+|&")
        Dim hardStrings As String = String.Empty
        Dim valueStrings As String = String.Empty
        Dim counter As Int16 = 0
    
        For Each str As String In txtSelection
            Dim tmpString As String = str.Trim
            If tmpString.StartsWith("""") Then
                hardStrings &= tmpString.Substring(1, tmpString.Length - 2)
            Else
                Dim fmt As String = String.Empty
                Dim indxToString As Int32 = 0
    
                If tmpString.ToLower.Contains(fmtdTostring) Then
                    indxToString = tmpString.ToLower.IndexOf(fmtdTostring)
                    fmt = tmpString.Substring(indxToString + 11, tmpString.Length - tmpString.ToLower.IndexOf(""")", indxToString) - 1)
                End If
    
                If fmt <> String.Empty Then
                    hardStrings &= "{" & counter.ToString & ":" & fmt & "}"
                    valueStrings &= tmpString.Substring(0, indxToString) & delimt
                Else
                    hardStrings &= "{" & counter.ToString & "}"
                    valueStrings &= tmpString & delimt
                End If
    
                counter += 1
            End If
        Next
    
        If valueStrings <> String.Empty Then valueStrings = valueStrings.Substring(0, valueStrings.Length - delimt.Length)
    
        textSelection.Text = String.Format(output, hardStrings, valueStrings)
        DTE.UndoContext.Close()
    
    End Sub