Can someone explain to me why my code:
string messageBody = "abc\n" + stringFromDatabaseProcedure;
where valueFromDatabaseProcedure is not a value from the SQL database entered as
'line1\nline2'
results in the string:
"abc\nline1\\nline2"
This has resulted in me scratching my head somewhat.
I am using ASP.NET 1.1.
To clarify,
I am creating string that I need to go into the body of an email on form submit.
I mention ASP.NET 1.1 as I do not get the same result using .NET 2.0 in a console app.
All I am doing is adding the strings and when I view the messageBody string I can see that it has escaped the value string.
Update
What is not helping me at all is that Outlook is not showing the \n in a text email correctly (unless you reply of forward it).
An online mail viewer (even the Exchange webmail) shows \n as a new line as it should.
I just did a quick test on a test NorthwindDb and put in some junk data with a \n in middle. I then queried the data back using straight up ADO.NET and what do you know, it does in fact escape the backslash for you automatically. It has nothing to do with the n it just sees the backslash and escapes it for you. In fact, I also put this into the db: foo"bar and when it came back in C# it was foo\"bar, it escaped that for me as well. My point is, it's trying to preserve the data as is on the SQL side, so it's escaping what it thinks it needs to escape. I haven't found a setting yet to turn that off, but if I do I'll let you know...
ASP.NET would use <br /> to make linebreaks. \n would work with Console Applications or Windows Forms applications. Are you outputting it to a webpage?
Method #1
string value = "line1<br />line2";
string messageBody = "abc<br />" + value;
If that doesn't work, try:
string value = "line1<br>line2";
string messageBody = "abc<br>" + value;
Method #2
Use System.Environment.NewLine:
string value = "line1"+ System.Environment.NewLine + "line2";
string messageBody = "abc" System.Environment.NewLine + value;
One of these ways is guaranteed to work. If you're outputting a string to a Webpage (or an email, or a form submit), you'd have to use one of the ways I mentioned. The \n will never work there.
You need to set a watch and see where exactly your database result string gets double escaped.
Adding two strings together will never double escape strings, so its either happening before that, or after that.
When I get the string out of the database, .NET escapes it automagically. However, the little # symbol is appended to the string, which I did not notice.
So it appeared to be non-escaped to my "about to go on holiday" eye inside the ide.
Therefore when the non-escaped \n was added to the string (as the whole string is no longer escaped), it would remove the # and show the database portion of the string escaped.
Gah, it was all an illusion.
Perhaps that holiday is overdue.
Thanks for your input.
If the actual string stored in the database is (spaces added for emphasis): "l i n e 1 \ n l i n e 2", then whatever stored it there probably has a bug. But assuming that is the exact string there, then the "abc\nline1\nline2" string is what happens when you look at the string which would print as "abcline1\nline2" in a debugger which escapes it (this is a convenience, allowing you to copy-paste out of the debugger straight into code without errors).
Short answer: .NET is not escaping the string, your debugger is. The code which writes a literal "\n" into the database has a bug.
Related
I have the following code which worked fine up to today:
string aName = dr["Name"].ToString();
if (!string.IsNullOrEmpty(aName))
aName = aName.Replace("'", #"\'");
For some reason it's replacing "Dominic's - CA" with "Dominic\\'s - CA"
This link shows exactly what the raw data looks like in the database
Any ideas on how the 2 backslashes are appearing?
Any ideas on how the 2 backslashes are appearing?
Yes. You're almost certainly looking at the string in the debugger. The actual string only has a single backslash. Log it, write it out to the console, display it in a form or whatever and you'll see that there's only one backslash.
Unfortunately the debugger "helpfully" escapes backslashes for you, giving you text which could appear as a string literal in C#. This has tripped up countless people, and I'm going to ask the VS team to try to either make it more obvious or do something to improve the situation...
This is my problem.
A user can enter text into a text area in the browser. Which is then emailed out to users.
What I want to know is that how do I handle carriage return? If I enter \r\n for carriage return, the email (which is a plain text email) has actual \r\n in it.
In other words:
On the SQL server end
Case 1:
if I do this before the email gets sent
(notice the line break after line 1)
update emails
set
body='line 1
line 2'
where
id=100
the email goes out correctly
Case 2:
update emails
set
body='line 1'+char(13) + char(10) +'line 2'
where
id=100
This email also goes out correctly
Case 3:
However if I do this
update emails
set
body='line 1 \r\n line 2',
where
id=100
the email would have the actual text \r\n in it.
How do I simulate case 1/2 through c# ?
SQL literals (at least those in SQL Server) do not support such escape sequences (although you can just hit enter within the string literal so that it spans multiple lines). See this answer for some alternatives if writing it as an SQL string is a requirement.
If running the SQL programmatically from C#, use parameters which will handle this just fine:
sqlCommand.CommandText = "update emails set body=#body where id=#id"
sqlCommand.Parameters.AddWithValue("#body", "line 1 \r\n line2");
Note that the handling of the string literal (and conversion of the \r and \n character escape sequences) happens in C# and the value (with CR and LF characters) is passed to SQL.
If the above didn't address the problem, keep reading.
4.10.13 The textarea element:
For historical reasons, the element's value is normalised in three different ways for three different purposes. The raw value is the value as it was originally set. It is not normalized. The API value is the value used in the value IDL attribute. It is normalized so that line breaks use "LF" (U+000A) characters. Finally, there is the form submission value. [Upon form submission the textarea] is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs, and in addition, if necessary given the element's wrap attribute, additional line breaks are inserted to wrap the text at the given width.
Note that CR and LF represent characters and not the two-character sequence of \ followed by either the r or n characters - this form is often found in string literals. If it appears as such then something is doing the incorrect conversion and putting (or leaving) the \ there. Or, perhaps there is some misguided "add slashes" hack somewhere?
As pointed out, while URL decode is likely wrong, it won't directly do this conversion. However, if the conversion happened previously before being "URL Encoded", then it will (correctly) decode to (incorrect) values.
In either case, it's a bug. So find out where the incorrect data conversion is introduced and fix it (attach a debugger and/or monitor the network traffic for clues) - the required information to isolate where is simply not present in the post.
Use whatever c#'s string replace method is to replace "\\r\\n" with "\r\n" and that should fix it.
I am trying to do html encode on the below string which has quotes , buts it not working
The server returns with quotes for the string
string serverString= **“Test hello,”** // this is returned from database
serverString =HttpUtility.HtmlEncode(serverString);
i am getting this result
�Test helloI,�
but still its not replacing and i am getting some diamond symbols on the asp.net page
Can anybody tell me what am i doing wrong.
The quote characters you're seeing are perfectly legitimate characters from an HTML standpoint, so they don't need to be encoded by HtmlEncode. What you're most likely seeing is an issue with your browser's encoding not supporting those characters. See http://www.htmlbasictutor.ca/character-encoding.htm for more information.
Are you sure it's not a rendering issue? You might try a font like "Arial Unicode MS" to make sure the browser is rendering the characters properly.
You should also verify the string returned from the database is correct.
Lastly, it could help to share how you're writing serverString to your response stream. Some ASP.NET controls expect text and HTML-encode for you while others expect HTML and do not.
This is because the server is returning fancy double quotes (that's not the technical name for them) instead of regular double quotes. You could do something like this:
string serverString= "“Test hello,”";
serverString = HttpUtility.HtmlEncode(serverString)
// Replaces fancy left double quote with regular one
.Replace("\u2018", "'")
// Replaces fancy right double quote with regular one
.Replace("\u2019", "'");
I am working with a project that includes getting MMS from a mms-gateway and storing the image on disk.
This includes using a received base64encoded string and storing it as a zip to a web server. This zip is then opened, and the image is retrieved.
We have managed to store it as a zip file, but it is corrupted and cannot be opened.
The documentation from the gateway is pretty sparse, and we have only a php example to rely on. I think we have figured out how to "translate" most of it, except for the PHP function stripcslashes(inputvalue). Can anyone shed shed any light on how to do the same thing in c#?
We are thankful for any help!
stripcslashes() looks for "\x" type elements within longer strings (where 'x' could be any character, or perhaps, more than one). If the 'x' is not recognised as meaningful, it just removes the '\' but if it does recognise it as a valid C-style escape sequence (i.e. "\n" is newline; "\t" is tab, etc.), as I understand it, the recognised character is inserted instead: \t will be replaced by a tab character (0x09, I think) in your string.
I'm not aware of any simple way to get the .net framework to do the same thing without building a similar function yourself. This obviously isn't very hard, but you need to know which escape sequences to process.
If you happen to know (or find out by inspecting your base64 text) that the only thing in your input that will need processing is a particular one or two sequences (say, tab characters), it becomes very easy and the following snippet shows use of String.Replace():
string input = #"Some\thing"; // '#' means string stored without processing '\t'
Console.WriteLine(input);
string output = input.Replace(#"\t", "\t");
Console.WriteLine(output);
Of course, if you really do simply want to remove all the slashes:
string output = input.Replace(#"\", "");
I've been writing code for ASP.NET since the start, and today I encountered something I've never seen before. Typically I've looked for line breaks in C# (when posted in ASP.NET from a textarea, for example) by expecting "\r\n". Now I'm using the MVC framework, and the text coming over the wire from a textarea simply has "\n" for line breaks.
Is there something going on in old school TextBox controls that normalizes the line breaks? Since MVC just uses the form data as-is, is this normal? Would love to get some insight.
I have made observation that the actual line break sequence differs from browser to browser.
If you have a multiline textarea on a page and the page is submitted then:
IE returns "\r\n" to indicate newlines. FF returns "\n" in this case.
I tested it somewhere along the end of 2006, so it may be different now.
I do not believe it could have anything to do with WebForms vs. MVC. Both just process submitted input and return it to you as it is.
If you wish to somehow process and replace these characters it would make sense doing it in the long-to-short order:
string userText = form["Text"];
userText = userText.Replace ("\r\n", "<br/>").Replace ("\r", "<br/>");
\n is the line ending variant on *nix-style systems. \r\n is Windows-specific line-ending behaviour.
If you're checking for line-endings and expose your interface to non-Windows environments, be sure to check not only for \r\n but also for \n alone.
Fore more background, check out the Newline article at Wikipedia.
I am using Environment.NewLine :
string userText = form["Text"];
userText = userText.Replace (Environment.NewLine, "<br />")
Also take a look at #Haacked's post about some newline textarea quirks.