New line character in VB.Net? - vb.net

I am trying to print a message on a web page in vb.net. I am trying to get the messages in new lines. I tried using the "\r\n" and the new line character. But this is getting printed in the page instead of it comming to the next line. Please let me know if there is any alternative.

Check out Environment.NewLine. As for web pages, break lines with <br> or <p></p> tags.

Environment.NewLine is the most ".NET" way of getting the character, it will also emit a carriage return and line feed on Windows and just a carriage return in Unix if this is a concern for you.
However, you can also use the VB6 style vbCrLf or vbCr, giving a carriage return and line feed or just a carriage return respectively.

The proper way to do this in VB is to use on of the VB constants for newlines. The main three are
vbCrLf = "\r\n"
vbCr = "\r"
vbLf = "\n"
VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.
C++ file path string: "c:\\foo\\bar.txt"
VB file path string: "c:\foo\bar.txt"
C# file path string: C++ way or #"c:\foo\bar.txt"

You need to use HTML on a web page to get line breaks. For example "<br/>" will give you a line break.

If you are using something like this.
Response.Write("Hello \r\n")
Response.Write("World \r\n")
and the output is
Hello\r\nWorld\r\n
Then you are basically looking for something like this
Response.Write("Hello <br/>")
Response.Write("World <br/>")
This will output
Hello
World
you can also just define "<br />" as constant and reuse it
eg.
Public Const HtmlNewLine as string ="<br />"
Response.Write("Hello " & HtmlNewLine)
Response.Write("World " & HtmlNewLine)

it's :
vbnewline
for example
Msgbox ("Fst line" & vbnewline & "second line")

Try Environment.NewLine.

Your need to use the html/xhtml break character:
<br />

you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:
System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))

In asp.net for giving new line character in string you should use <br> .
For window base application Environment.NewLine will work fine.

VbCr
Try that.

In this case, I can use vbNewLine, vbCrLf or "\r\n".

vbCrLf is a relic of Visual Basic 6 days. Though it works exactly the same as Environment.NewLine, it has only been kept to make the .NET api feel more familiar to VB6 developers switching.
You can call the String.Replace() function to avoid concatenation of many single string values.
MsgBox ("first line \n second line.".Replace("\n", Environment.NewLine))

Environment.NewLine or vbCrLf or Constants.vbCrLf
More information about VB.NET new line:
http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

I had the need to store line breaks in a string in a SQL table and have them displayed in vb.NET. My solution was to include a string like this in my database:
"This is the first line{0}This is the second{0}This is the third"
In vb.NET, I processed the string like this before using it:
Label2.Text = String.Format(stringFromSQLquery, vbCrLf)
This replaces every occurance of {0} with vbCrLf

Related

Email body line by line

I use email to send my emails out. In body clause i use this code below. In bodyText variable i insert text comming from stringbuilder. However at the end when my email is received all text are not line b line but in one line. What am i doing wrong?
Mail.Body = "<HTML><HEAD></head><BODY style='font-size: 11px; font-family: Tahoma'>" + "<P>" & "Hi there," & ",</p>" + "<p>" & bodyText & "</p>" & "<p>This e-mail is generated automatically therefore <b>do not reply to this email.</b></p>" + "<p>Developer, </p>" & "Development team" & "</BODY></HTML>"
Stringbuilder:
_strbuild.Append("Start" + Environment.NewLine).AppendLine()
_strbuild.Append("Start" + Environment.NewLine).AppendLine()
You create some HTML so you have to use the HTML new line (<br>):
_strbuild.Append("Start" + "<br>")
_strbuild.Append("Start" + "<br>")
Instead of using the system new line (\r\n or \n) you have to use the <br> element. In HTML you can use the system new line only to format the HTML code not to format the output.
When the body of the message is sent in HTML format, add the (break - br) tags right in your String. vbCrLf and StringBuilder are not suggested as they don't work if the body is in HTML format.
Dim mail As New MailMessage
mail.IsBodyHtml = True
mail.Body = "Line one<br>"
mail.Body += "Line Two<br>"
mail.Body += "More Lines"
Environment.NewLine does not work because the current environment for your program is not the same environment where the user will read your result. Your environment is a console program (masquerading as a scheduled task or service), or web server application, or windows form, or something else where outputting a simple \n character results in a new line. The same applies to AppendLine(). It's using Environment.NewLine behind the scenes, and again, the problem is that your program environment is different than your user's environment.
In this case, your user's environment is an html document. HTML treats all simple whitespace the same, as a single space. This is true whether you have a tab, newline, space, or any multiples or combination of the above. It all consolidates to a single space in html.
So for html, in order to force a line break, you should instead include a <br> tag with your html. More than this, HTML will break up the lines automatically; you might get away without doing anything. Even in cases where you want an explicit line break what you're typically really doing from a semantic standpoint is asking for a new paragraph. This means <p> is commonly more appropriate:
_strbuild.Append("Start").Append("<p>")
If you really don't want the extra blank line from the new paragraph you can use styles to remove or reduce it (though admittedly e-mail is the one place where breaking the correct p vs br semantics might be appropriate: e-mail renderers can be difficult).

Escape Characters in a resource file string?

I've been globalizing an application and have been using Resx Manager to make my life easier. I ran into a multi-line string literal and it stumped me.
How would I handle the escape characters when making this string into a resource?
If Not RelayMessage(
"Are you sure you want to do the selected action?" & vbCrLf &
"A confirmation message will be sent to the user." & vbCrLf &
"Please ensure you want to perform this action before hitting accept.",
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
How would I make that string into a resource?
In the standard VS resource manager (is this the manager you're using?) you can enter a multi-line string resource directly in the editor by using shift-Enter:
Note that this is actually stored as a string with CR+LF pairs, assisted by the space="preserve" attribute. Viewing the .resx file in a text editor:
Results using a standard message box:
MessageBox.Show(strings.myString)
I don't know how it is usually handled in globalization problems. But an easy way would be to define your own escape character formats. For example you could define \n as a newline character. When you actually use your ressource you could then use
If Not RelayMessage(Strings.Replace(myResourceString, "\n", vbCrLf),
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
instead of
If Not RelayMessage(myResourceString,
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
Or you could manually add chars with character codes 10 and 13 (e.g. ChrW(10) & ChrW(13)) at the vbCrLf location in your ressource string. This equals a vbCrLf (meaning a carriage return (10) + line feed (13)). This would avoid manipulation of the source code. Other stuff like Tab (9) have codes, too. These are called control characters. Take a look at the wikipedia http://en.wikipedia.org/wiki/Control_character

FileSystem.WriteAllText adds non-printable characters

Here are two methods for writing text to a file in VB.Net 2012. The first one prepends the same three non-printable characters to each file: . The second one works as expected and does not add the three characters. objDataReader is an OleDB datareader.
Any idea why?
Greg
My.Computer.FileSystem.WriteAllText(lblLocation.Text & "\" &
objDataReader("MessageControlId").ToString & ".txt", objDataReader("MsgContents").ToString, False)
Using outfile As New StreamWriter(lblLocation.Text & "\" & objDataReader("MessageControlId").ToString & ".txt")
outfile.Write(objDataReader("MsgContents").ToString)
End Using
Thanks. I found the entry below I after Googled BOM, in case anyone wants a more detailed explanation. While the BOM was not visible in a text editor it did cause problems when I passed the file to our HL7 interface engine.
Greg
Write text files without Byte Order Mark (BOM)?

vbCrLF or Environment.NewLine

I use Environment.NewLine, my colleagues use vbCrLf.
When I'm doing a code review for them I want something that I can point to to say "use Environment.NewLine instead of vbCrLf"
Or, am I just peeing in the wind, and it doesn't really matter ?
Environment.NewLine is more portable, making to code easier to be read by someone coding in C#. Technically vbCrLf is a constant, where NewLine is not. This is because on a different OS, NewLine may not return CR/LF. On Unix it would just be LF.
Another point is that Environment.NewLine expresses the intended meaning more clearly. In most cases, the goal is Place a newline in this string, not Place carriage-return and line-feed characters in this string. Environment.NewLine states what to do, vbCrlf states how to do it.
In most cases, either one will work correctly.
However, if you are developing on Mono and use Environment.NewLine on a Unix OS, then you will get different results (\n (LF) instead of \r\n (CRLF)).
In addition, if you ever want/need to port your code to C#, Environment.NewLine will not have to be updated whereas vbCrLf will.
Environment.NewLine is portable in .NET and for someone unfamiliar with VB it is more readable than vbCrLf.

Converting characters to ASCII code

Need help with reading special characters within my VB code. ASCII code Char(34) = " works fine but Char(60) = < and Char(62) = > are not being read.
My Code
node.FirstChild.InnerText = Chr(60) & "httpRuntime executionTimeout=" & Chr(34) & "999999" & Chr(34) & " maxRequestLength=" & Chr(34) & "2097151" & Chr(34) & "/" & Chr(62)
Without ASCII Code
'node.FirstChild.InnerText = "<httpRuntime executionTimeout="999999" maxRequestLength="2097151"/>"
Are you trying to modify a Config file? Try:-
node.FirstChild.InnerXml = "<httpRuntime executionTimeout=""999999"" maxRequestLength=""2097151"" />"
Note all that Chr marlarky is unnecessary, were you trying to avoid < and > being encoded as XML entities?
Maybe this doesn't answer your question, but you could use two double quotes to escape the quotes character in VB.NET:
node.FirstChild.InnerText = _
"<httpRuntime executionTimeout=""999999"" maxRequestLength=""2097151"" />"
I'm just guessing: you could use the String.Format method for your purposes:
node.FirstChild.InnerText = _
String.Format( _
"<httpRuntime executionTimeout=""{0}"" maxRequestLength=""{1}"" />", _
timeoutValue.ToString(), reqLenValue.ToString())
You'll need to give more information about how you're "seeing" the results. In my experience, problems with this are as likely to be about viewing strings in the debugger as getting the right strings in the first place.
I don't really see why you need to use Chr(60) etc at all, other than for the quotes. What happens when you just use < and > in your code?
I strongly suggest you dump the string out to the console rather than using the debugger - the debugger tries to show you how you could represent the string in code, rather than showing you the contents verbatim.
Of course, if this is XML then I'd expect serializing the XML out again to end up escaping the < and > - again, more information about what you're trying to do would be helpful. The absolute ideal (IMO) would be a short but complete program demonstrating the problem - a small console app which does one thing, and a description of what you want it to do instead.