escaping characters - c#

How can I escape the Quotes so that this statement
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+""");combo.showDropDown(true);}</script>";
reads like this
function ShowDropDown() {
var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox");
combo.showDropDown(true);
}
EDIT- UPDATE
I might of asked the question wrong because i keep getting different errors. If I put the javascript directly on the page normally the function works. When I inject the javascript this way it doesnt work
I am doing this in code behind
string sScript =#"<script language='javascript'> function ShowDropDown(){ var combo = $find("""+this.ClientID+#"""); combo.showDropDown(true); } </script>";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoopendropdown", sScript, false);
OnClientFocus = "ShowDropDown()";
it gets generated this way
<script language='javascript'> function ShowDropDown(){ var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox"); combo.showDropDown(true); } </script>
but the variable combo is null and thats what the problem is. I cant figure out why when it is registered with code-behind it doesnt work and when write it normally on the page it does.

Simple way: Add the same # at the beginning of the second string literal:
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+#""");combo.showDropDown(true);}</script>";
Better way: use string.Format
string sScript = string.Format(
#"<script language='javascript'>
function ShowDropDown(){
var combo = $find(""{0}"");combo.showDropDown(true);
}
</script>",
this.ClientID);
(Best way: separate concerns using unobtrusive javascript.)

string sScript = "<script language='javascript'>\n" +
"function ShowDropDown() {\n" +
" var combo = $find(""" + this.ClientID + """);\n" +
" combo.showDropDown(true);\n" +
"}\n" +
"</script>";

The escape for double quotes in C# (and most C family languages) is \"
Or you could just use single quotes since it's valid in JavaScript.

If I understand your question correctly, you want to concatenate this.ClientID with the rest of the script.
You can do this using the String.Format method like so:
string scriptFormat = #"<script language='javascript'>function ShowDropDown(){var combo = $find(""{0}"");combo.showDropDown(true);}</script>";
string sScript = String.Format(scriptFormat, this.ClientID);
Note that inside a verbatim string literal, "" produces a single " character.

You can escape them using the \ character.
For a complete list of escape combinations, see section 2.4.4.4 Character literals of the C# language specification.

NOTE: language is deprecated for script tags, use type
string sScript =#"
<script type='text/javascript'>
function ShowDropDown(){
var combo = $find(""" + this.ClientID + #""");
combo.showDropDown(true);
}
</script>";

Related

C# double " mark in textstring

hi guys I made an app to extract .lua file when I push the button
my problem is I need to pass this string like this
QUESTID = LuaGetQuestID("QNO_QUEST_AR")
QNO_QUEST_AR extracted from textBox1 so my code =
File.Write(" QUESTID = LuaGetQuestID("+textBox1.Text+")\r\n");
I need to add 2x " mark like this (""+textBox1.Text+"")
anyway to do that ? thanks
You can use a 'verbatim identifier' (#) and escape quotes with double quotes.
Note that you can also combine the 'string interpolation identifier' ($) so that you're not building up the string with pluses. See:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
and
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Then you could write your code something like:
var myString = #$"QUESTID = LuaGetQuestID(""{textBox1.Text}"")";
thanks, guys it works with this code
File.Write(" QUESTID = LuaGetQuestID(" + '"' + textBox1.Text + '"' + ")\r\n");

How to parse JSON objects with double quotes in one of its property values

If I have a json string, with one of its property values having a double quote in it, I am not able to parse it.
For example, if my object is { "Name" : "Six \" Pipe" } then the following gives me an error - Unexpected token P.
var str = '{ "Name" : "Six \" Pipe" }';
JSON.parse(str); //error
$.parseJSON(str); //error
The string is formed in a razor view as follows -
var str = new JavaScriptSerializer().Serialize(obj);
And then in JavaScript I am doing
var obj = JSON.parse('#(Html.Raw(str))');
How can I parse such strings?
You should escape the backslashes since in JS it will only \" will be converted to " and will make the JSON incorrect. The blackslash is discarded by javascript.
so the correct string would be-
var str = '{ "Name" : "Six \\" Pipe" }';
JSON.parse(str); //works
Edit:
So, if you want to create a literal backslash in JS, you have to escape it. You can do this while creating this string and double-escaping the key's value. One way to tackle this could be -
To html encode the strings (key values) just like: " instead of \" etc. This seems straight forward to me with .Net. I'm not sure but HttpServerUtility.HtmlEncode could help. Then on the javascript side you could be able to parse straight away- fiddle
I encountered same issue. After spending a lot of time trying to deal with that quotes I came to this solution
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj = new {name = "\"Name1\""};
var objJson = serializer.Serialize(obj);
}
<script>
var jsObject = #Html.Raw(objJson);
</script>
I use json as js object without any parsing, html result will be like
<script>
var jsObject = {"name":"\"Name1\""} ;
</script>
which is correct JavaScript. Hope it will be helpfull for somebody

Pass parameters through URL in C# ASP.net

I have the following code for a Button click event where I open a new Tab for a Report and I need to pass a parameter to that from the code behind,
String classname = txt_classname.SelectedValue;
String teachername = "Some name";
string url = "Report_Classwise.aspx";
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
I need to pass classname & teachername to Report_Classwise.aspx page, I have tried setting
string url = "Report_Classwise.aspx?classname='"+classname+"'&teachername='"+teachername+"'";
But it didn't work
You dont need to add additional single quote in URL
string url = "Report_Classwise.aspx?classname=" + classname + "&teachername="
+ teachername;
You single quotes might interfere with your parameter names, are you sure you really want to have them there?
You might want to encode your parameters to make sure that they don't contain some special characters etc, and drop your single quotes:
string url = "Report_Classwise.aspx?classname=" + encodeURIComponent(classname) +"&teachername=" + ncodeURIComponent(teachername);
Use string.Format for more readability and avoid confusions.
string url = string.Format("Report_Classwise.aspx?classname={0}&teachername={1}", classname, teachername);

Issue with forming a string with double quotes

I want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";

String escaping issue with Roslyn statement creation

I've the following code, which builds up a Roslyn statement which calls Roslyn code inside, but I've a problem with string escaping.
Here is the code:
var parseStatementArgument = "var statement = Syntax.ParseStatement(\\\"Console.WriteLine (\\\"Hello {0}\\\", parameter1);\\\");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "\"" + parseStatementArgument + "\"",
value: parseStatementArgument)
)));
var variableDeclarator = Syntax.VariableDeclarator(Syntax.Identifier("statement"))
.WithInitializer(Syntax.EqualsValueClause(st));
var varStatement = Syntax.VariableDeclaration(Syntax.IdentifierName("var"), Syntax.SeparatedList(variableDeclarator));
var varStatementText = varStatement.Format().GetFormattedRoot().GetFullText() + ";";
var scriptEngine = new ScriptEngine(
new [] {
MetadataReference.Create("Roslyn.Compilers"),
MetadataReference.Create("Roslyn.Compilers.CSharp"),
MetadataReference.Create("Roslyn.Services"),
MetadataReference.Create("Roslyn.Services.CSharp")
},
new [] {
"System",
"Roslyn.Compilers.CSharp",
"Roslyn.Scripting",
"Roslyn.Scripting.CSharp",
"Roslyn.Services"
});
var session = Session.Create();
scriptEngine.Execute(varStatementText, session);
scriptEngine.Execute("Console.WriteLine (statement.Format().GetFormattedRoot().GetFullText());", session);
The problem is that the "statement" printed to the console windows via the script engine execution will miss the backslashed around the "Hello {0}" string. If I add double escaping (additional \ into the parameter, Roslyn will raise compile errors about missing commas.
How may I update this code to get a syntactically correct version of what I want into the statement variable?
How about switching to using verbatim string levels, and just add another level of escaping as you add the node.
Something like:
var parseStatementArgument = #"var statement = Syntax.ParseStatement(#""Console.WriteLine (""""Hello {0}"""", parameter1);"");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "#\"" + parseStatementArgument.Replace("\"", "\"\"") + "\"",
value: parseStatementArgument)
)));
Based on Kevin's tip on how to replace string for literals I played around and found this as a solution that works, but it raised another problem.
The solution:
var parseStatementArgument = "var statement = Syntax.ParseStatement(\\\"Console.WriteLine (\\\\\\\"Hello {0}\\\\\\\", parameter1);\\\");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "\"" + parseStatementArgument + "\"",
value: parseStatementArgument.Replace ("\\\\\\", "\\"))
)));
Now it correctly outputs a code snippet which is syntactically correct and compiles well.
The problem it raises is that I had to modify the source string and not the derived string to get the correct result. When rewriting code or generating code with Roslyn it can not be a requirement to double or triple escape string literals to make Roslyn able to deal with that correctly, maybe its a Roslyn issue, I hope that someone will shed some light on an elegant solution which works for all kind of strings.

Categories

Resources