Embed Code and Avoid Underscores in Your Multiline Strings

Embed Code and Avoid Underscores in Your Multiline Strings

  • Comments 26

One of the things I most dearly missed from FoxPro when I moved to VB.NET was the ability to easily dump a bunch of text (multi-line string literals) into the editor easily and embed code (text-merge). FoxPro has a keyword TEXT...ENDTEXT for this and I used to use it all the time. In VB it gets pretty darn ugly with any large amount of text because you have to concatenate string literals with your code and use underscores for readability.

  Dim oldWay = "this is a string" & vbCrLf & _

               "with formatting" & vbCrLf & _

               "and stuff" & vbCrLf & _

               "look ma, underscores" & vbCrLf & _

               "         tabs too"

 

  MsgBox(oldWay)

Not any more. With Visual Basic 9's built in XML literals support we can now easily write a bunch of text directly into the editor:

         Dim newWay = <string>

this is a string

with formatting

and stuff

look ma, no underscores!!!

            tabs too

                </string>

 

        MsgBox(newWay.Value)

The text formatting is preserved as well. All you have to do is get the .Value of the XElement, which is the string literal. As you can see this is much cleaner than what we're used to. And if you still like to see your string literals in the default reddish color, you can easily change the color settings for VB XML literals in Tools --> Options --> Environment --> Fonts and Colors, then select "VB XML Text" and set the custom color to RGB(163,21,21). Here's another example, some SQL query text (now with the reddish color): 

        Dim query = <query>

SELECT Customers.*, Orders.OrderDate

FROM Customers

    INNER JOIN Orders ON Orders.CustomerID = Customers.CustomerID

WHERE Customers.CustomerID = @CustomerID

                    </query>

 

        Dim cmd As New SqlCommand(query.Value)

        cmd.Parameters.AddWithValue("@CustomerID", id)

Now here's where it gets fun. You can also embed expressions into these literals with the <%= syntax. This means you can do any kind of text merging much cleaner than ugly concatenation of strings with code or use of String.Format especially as the size of the text increases. Here's some simple examples:

        Dim simple = <string>

This is a simple text merge example:

Hello, <%= Environment.UserName %>

                     </string>

 

        MsgBox(simple.Value)

 

 

        Dim controls = <string>

There are the following controls on this form:

<%= From item In Me.Controls Select item.ToString & vbCrLf %></string>

 

        MsgBox(controls.Value)

Calvin has some good examples here and here on how to generate scripts dynamically, but here's one that uses a simple code generation pattern. 

Private Sub CreateClass()

        Dim CustomerSchema As XDocument = XDocument.Load(CurDir() & "\customer.xsd")

 

        Dim fields = From field In CustomerSchema...<xs:element> _

                     Where field.@type IsNot Nothing _

                     Select Name = field.@name, Type = field.@type

 

 

        Dim customer = <customer>

Public Class Customer

    <%= From field In fields Select <f>    

        Private m_<%= field.Name %> As <%= GetVBPropType(field.Type) %></f>.Value %>

 

        <%= From field In fields Select <p>    

        Public Property <%= field.Name %> As <%= GetVBPropType(field.Type) %>

            Get

                Return m_<%= field.Name %> 

            End Get

            Set(ByVal value As <%= GetVBPropType(field.Type) %>)

                m_<%= field.Name %>  = value

            End Set

        End Property</p>.Value %>                       

End Class</customer>

 

        My.Computer.FileSystem.WriteAllText("Customer.vb", customer.Value, _

False, System.Text.Encoding.ASCII)

 

    End Sub

 

    Private Function GetVBPropType(ByVal xmlType As String) As String

        Select Case xmlType

            Case "xs:string"

                Return "String"

            Case "xs:int"

                Return "Integer"

            Case "xs:decimal"

                Return "Decimal"

            Case "xs:boolean"

                Return "Boolean"

            Case "xs:dateTime", "xs:date"

                Return "Date"

            Case Else

                Return "'TODO: Define Type"

        End Select

    End Function

I hope this gives you some good ideas on what you can do with XML Literals. You literally (pun intended ;-)) don't have to use them to produce XML, you can use them to produce any text-based output.

Enjoy,
-B

Leave a Comment
  • Please add 4 and 4 and type the answer here:
  • Post
  • should be able to

    dim s as string

    s = |

    This is

    a

    multiline

    string|

    VB and LotusScript supported this simple method.  Using the suggested xml text is buggy.  You will get errors in Studio 08 depending on what is in  the text (and its all text with no <> substitutions).  I can't use the suggestion above because it only sometimes works and isn't predictable.

  • Hi vbuser,

    Can you show me an example of text that won't work?

    Thanks,

    -B

  • Beth,

    I really like this.  I used the Text/EndText in VFP to write my SQL strings and it would be easy to copy commands between VFP and Query Analyzer.

    Using your new construct, I am having problems with the following code where the visual studio compiler is giving me errors.  It appears to not like my "less than" sign in the middle of the string... any ideas?

           Dim sProblem = <myxml>select * from detailinfo where isnull(FaxedDate, '1900-1-1') < '1901-1-1'</myxml>

  • Hi Dan,

    Remember that this is XML. All XML parsing rules apply so you cannot place < or > characters in the element. Here is a list of XML Entities that are reserved: http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML

    However you can still render them by using the entity's name instead. In your example it would be:

    Dim sProblem = <myxml>select * from detailinfo where isnull(FaxedDate, '1900-1-1') &lt; '1901-1-1'</myxml>

    MsgBox(sProblem.Value)

    HTH,

    -B

  • Beth,

    Thank you for the quick response.  Just couple more questions, my "coding police" wont let me use variants in my declarations.  What is the datatype that is used for this?  Also, as I try this in a few of my projects, I get very long error messages about system.xml is not available, eventhough it is listed at the top of the module.

    dim sProblem as ???

  • Hi Dan,

    You're using Visual Studio 2008 and Visual Basic 9 so the compiler will automatically infer the type of the variable. This is specified by Option Infer ON (which is the default in new projects). You should have Option Strict, Explicit and Infer all ON. Your statement above is not an Object (no variants in .NET ;-)) it is inferred by the compiler and still is strongly typed. Just hover over the variable and you should see the type of it. In this case it is an XElement. But you can be explict and say Dim sProblem as XElement = ... if that appeases the gods. It's just more typing ;-)

    HTH,

    -B

  • ok, last question I hope.  As I try this on a project that was upgraded from VS2005 to VS2008, I get an error message that reads "XML literals and XML axis properties are not available.  Add references to System.xml, System.xml.linq, and system.core.

    System.xml is already part of the project, and it won't allow me to add system.xml.linq.  any ideas what I am missing?

  • Hi Dan,

    You'll need to set the framework target to 3.5 first.

    See:

    http://msdn.microsoft.com/en-us/library/07bysfz2.aspx

    and

    http://msdn.microsoft.com/en-us/library/bb398197.aspx

    HTH,

    -B

  • Beth,

    Someone just asked me to do this in C#.  I love the ability to have the XML evalualated in the middle of the string with the <%=variable name%>.  Do you know how I would do the same thing in C#?

    I tried translating the statements, but I got stuck.  If you could translate your "simple" example above, I can take it from there.

    Thanks for everything.

    Dan

  • Hi Dan,

    C# doesn't support XML literals syntax. You'll need to call the LINQ to XML API directly.

    http://msdn.microsoft.com/en-us/library/bb387061.aspx

    HTH,

    -B

  • Thanks for the info! I just came from VFP background. And i was looking for Text//EndText alternate in VB.NET

    and its big life saver to me. Again Thanks for sharing! :)

Page 2 of 2 (26 items) 12