line break in alert popup - c#

I am trying to add a new line Javascript alert message. I tried '\n' and 'Environment.NewLine'. I am getting Unterminated string constant error. Could you please let me know what could be the problem? I appreciate any help. I also tried \r\n.
string msg = "Your session will expire in 10 minutes. \n Please save your work to avoid this.";
if (!this.ClientScript.IsStartupScriptRegistered(ID))
this.ClientScript.RegisterStartupScript(GetType(), ID, String.Format("<script language=JavaScript>setTimeout(\'alert(\"{1}\");\',{0}*1000);</script>", sTime, msg));

I would suspect that you need to change your code to;
string msg = "Your session will expire in 10 minutes. \\n Please save your work to avoid this.";
And escape the \n otherwise your code outputted would actually include the line break rather than \n
Your output code would look like:
setTimeout('alert("Your Session....
Please save your work to ....");', 1000);
Rather than:
setTimeout('alert("Your Session....\n Please save your work to ....");', 1000);

I'm not sure, but I think that \n is escaped in the string.Format method, like \". Maybe you should use \\n instead.
Edited : and the first \ of \\n has been escaped when i posted that. xD

At first glance I would say the primary problem is that you're escaping the ' character around your alert. Since your string is defined by the double quotes, you don't need to escape this character.

add "#" at the beginning of your string - like this:
string msg = #"Your session ....";

The code looks fine, so I'm going to guess that you're using a message that itself has a ' quote in it, causing the JS syntax error. For inserting dynamic text into a Javascript code block, you really should use JSON to make your C# strings 'safe' for use in JS.
Consider JSON the go-to method for preventing the JS equivalent of SQL injection attacks.

Adding a # at the beginning should help.

Related

Replace ' with \' for some reason puts \\'

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...

Replacing backslash in a string

I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

escape double quotes inside string literal in C#

i need a regex in c# that will escape double quotes inside string literal. so if i have this string: "How about "this" and how about "that"". i will be able to use it in javascript without errors. because i am writing this literal to the page as js var.
EDIT: i will try to explain more about the problem.
i writing messege to the page like this:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", UserMsg, Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
now lets say messege 999 is this: "we found a "problem" in your details".
this is causing js errors.
You should not use regular expressions to escape your C# strings into a JavaScript friendly / safe format. Instead, assuming you are using .NET 4, you can use HttpUtility.JavaScriptStringEncode and it's overload to take care of both single and double quotes for you.
For example:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", HttpUtility.JavaScriptStringEncode(UserMsg), Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
Would ouput the following with UserMsgset to "we found a "problem" in your details":
var UserMsg ="we found a \"problem\" in your details";
Assuming I understand you correctly, to escape a " in C# source code, you can do it like this:
"\""
or
#""""
Either of those literals defines a string containing single double quote character.
On the other hand perhaps you need to know how to escape the quote character in Javascript. That is done with \". You can use String.Replace() to effect that but you would be much better off with a proper HTML/JS emitter library.
See the Web Protection Library (also known as AntiXSS). That has a JavascriptEncode method to do this and other escapes.
Here is my suggestion for you:
var regex = new Regex("\"");
var result = regex.Replace(stringToReplace, "\\\"");
I believe something like this may work:
Regex.Replace(myString,'"',"");
I think your question has been answered already but if you still need the complete code.
below piece of javascript would work for you.
var s = "this is \"Hi \" ";
alert(s);
Praveen

Regex Pattern to Extract Email Data

I'm retrieving raw text (includes header, and message) from a POP server. I need to capture everything after the header which is terminated by a blank line between it and the user message.
At the same time I'm wanting to ignore anything from original messages if it's a reply. The start of a reply for the emails I'm parsing start with
------Original Message------
An example email might look like this
Return-Path: ...
...
More Email Metadata: ...
Hello from regex land, I'm glad to hear from you.
------Original Message------
Metadata: ...
...
Hey regex dude, can you help me? Thanks!
Sincerely, Me.
I need to extract "Hello from regex land, I'm glad to hear from you." and any other text/lines prior to the original message.
I'm using this regex right now (C# in multiline mode)and it seems to work except it's capturing ------Original Message------ if the body is blank. I'd rather just have a blank string instead.
^\s*$\n(.*)(\n------Original Message------)?
Edit
I haven't down voted anyone and if you happen to downvote, it's usually helpful to include comments.
The reason for this is that you have an extra \n inside the parenthesis. If the body is blank, there is no extra newline there. Therefore, try this:
^\s*$\r\n(.*)(^------Original Message------$)?
If you don’t want the newline at the end of the body, you can still use string.Trim() on the matched part.
Note: This assumes that the input uses \r\n line terminators (which is required in e-mail headers according to the MIME standard).
Why don't you not use DotnetOpenMail? Using a regex to do this is a wrong approach, you'd be better off using a dedicated email handler instead....
You need to replace (\n------Original Message------) with (?=(\n------Original Message------)) lookahead to not return that part, just to ensure it's there

Newlines escaped unexpectedly in C#/ASP.NET 1.1 code

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.

Categories