I want to add double quotes for a sting . I know by using /" we can add double quotes . My string is
string scrip = "$(function () {$(\"[src='" + names[i, 0] + "']\"" + ").pinit();});";
When i do this on the browser i am getting " instead of " quotes . How can i overcome with the problem ?
If your browser has displayed a """ instead of a " character, than there are only a few causes possible. The character should have been emitted to the browser as either itself, or as a HTML entity of ". Please note the semicolor at the end. If a browser sees such 'code', it presents a quote. This is to allow writing the HTML easier, when its attribtues need to contain special characters, compare:
<div attribute="blahblahblah" />
if you want to put a " into the blahs, it'd terminate the attribute's notation, and the HTML code would break. So, adding a single " character should look like:
<div attribute="blah"e;blahblah" />
Now, if you miss the semicolon, the browser will display blah"blahblah instead of blah"blahblah.
I've just noted that your code is actually glueing up the JavaScript code. In JavaScript, the semicolon is an expression delimiter, so probably there is actually a " in the emitted HTML and it is just improperly presented in the error message... Or maybe you have forgotten to open/close some quotes in the javascript, and the semicolon is actually treated as expression terminator?
Be also sure to check why the JavaScript code undergoes html-entity translation. Usually, blocks are not reparsed. Are you setting that JavaScript code as a HTML element attribute? like OnClick or OnSend? Then stop doing it now. Create a javascript-function with this code and call that function from the click/send instead.. It is not worth to encode long expressions in the JS into an attribute! Just a waste of time and nerves.
If all else fails and if the JavaScript is emitted correctly, then look for any text-correcting or text-highlighting or text-formatting modules you have on your site. Quite probable that one of them is mis-reading the html entities and removed the semicolon, or the opposite - that they add them were they are not needed. The ASP.Net itself in general does its job right, and it translates the entites correctly wherever they are needed, so I'd look at the other libraries first.
You can use something like this:
String str=#"hello,,?!"
This should escape all characters
Or
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
Here's the manual: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
What else are you doing with the string?
Seems that somewhere after that the string gets encoded. You can could use HttpUtility.HtmlDecode(str); but first you'll have to figure out where your string gets encoded in the first place.
Keep in mind that if you use <%: %> in aspx or #yourvarin Razor it will get encoded automatically. You'll have to use #Html.Raw(yourvar) to suppress that.
Related
I'm having problems creating a query string and sending it to another webpage.
The text I'm trying to send is long and has special characters. Here is an example:
Represent a fraction 1/𝘣 on a number line diagram by defining the interval from 0 to 1 as the whole and partitioning it into 𝘣 equal parts. Recognize that each part has size 1/𝘣 and that the endpoint of the part based at 0 locates the number 1/𝘣 on the number line.
I can send this just fine if I hand code it:
<a href="Default.cshtml?standardText=Represent a fraction 1/𝘣 on a number line diagram by defining the interval from 0 to 1 as the whole and partitioning it into 𝘣 equal parts. Recognize that each part has size 1/𝘣 and that the endpoint of the part based at 0 locates the number 1/𝘣 on the number line.">
Link Text
</a>
This goes through without any problems, and I can read the entire Query String on the other side.
But if I am creating the link programmatically, my query string gets cut off right before the first character reference. I am using the following setup in a helper function:
string url = "Default.cshtml";
url += "?standardText=" + standard.text;
Link Text
When I use this, I only get "Understand a Fraction as 1/" and then it stops.
When I look at the page source, the only difference in the links is that one has actual ampersands and the second is having those turned into &
<a href="Default.cshtml?standardText=Understand a fraction 1/𝘣 as the quantity formed by 1 part when a whole is partitioned into 𝘣 equal parts; understand a fraction 𝘢/𝑏 as the quantity formed by 𝘢 parts of size 1/𝘣."
So the problem is not really the spaces, but the fact that the & is being interpreted as starting a new query string parameter.
I have tried various things [using HttpUtility.UrlEncode, HttpUtility.UrlEncodeUnicode, Html.Raw, trying to replace spaces with "+"], but the problem isn't with the spaces, its with how the character references are being handled. When I tried HttpUtility.urlEncode I got a double-encoding security error.
On the advice of OmG I tried replacing all the &s, #s, and /s using:
url = url.Replace("&","%26");
url = url.Replace("#","%23");
url = url.Replace("/","%2F");
This led to the following link:
All Items
And now when I click on the link I get a different security warning/error:
A potentially dangerous Request.QueryString value was detected from the client (standardText="...raction 1/𝘣 as the qua...").
I don't see why it is so hard to send character references through a QueryString. Is there a way to prevent Razor from converting all my &s to the & ; ? The address works fine when it is just plain "&"s.
Update: using URLDecode() on the string does not affect its character entity references, so when I try to decode the string then re-encode it, I still get the double-escape security warning.
Update: on the suggestion of #MikeMcCaughan, I tried using JS, but I am not very knowledgeable about mixing JS and Razor. I tried creating a link by dropping a script into the body like so:
<script type="text/javascript">
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = encodeURIComponent(#url);
document.body.appendChild(a);
</script>
But no link showed up, so I'm obviously doing it wrong.
For reference, when I try to use #Html.Raw(url),
Link Text
The &s are still turned into & ;s. the link renders as:
Link text
One simple solution is replacing the special characters by their encoding which can be accessed from here.
As you can find, replace in the string & with %26 using .replace for string. Also, replace / with %2F, # with %23, ; with %3B, and space with %20.
Also, You can do these in C# by the following function:
Server.URLEncode("<The Url>")
and in Javascript by the following function:
encodeURI("<The Url>")
Also, as you know the double-encoding is this. To prevent the double-encoding, you should have not encoded some part of the string before passing the string into the Server.URLEncode function.
hi guys this is a silly but small and important one for me.
I have a jQuery that picks up a bit of string that has single quotes and results in not picking them up at all. i.e.
data-name='someone's name';
The jQuery that picks up the code
$('#id').text($(this).data("name"));
My guess is jQuery enclosing is '' rather "" so the ' in someone's name is closing the hence this results in someone
So I was trying to do the following--
string name = "someone's name";
//Attempted replace here
<div data-name='<%# Eval("name").ToString().Replace("'","\'") %>'></div>
But I'm getting Parser Error Message: The server tag is not well formed.
What am I doing wrong?
Trivially use double quotes data-name="someone's name"
To deal with strings that may contain either quotes you need to encode as HTML entities:
HttpUtility.HtmlAttributeEncode("someone's name") yields someone's name
(You need to use outer " as the quote for this to work correctly)
I need to be able to access strings held in my C# code in JavaScript. To test, I have tried displaying a message box with the C# string in JavaScript (I am using this string literal and the message box as an example scenario):
alert(<%: "TEST" %>);
When this code runs, no message box is displayed. On the other hand, a message box is displayed with this code:
alert(<%: 6 %>);
Why is it that I can use integers but not strings? Is there any way around this?
Thanks.
You need to add quotes around the string; otherwise, the browser sees alert(TEST);, which is incorrect. To prevent cross-site scripting attacks, you also need to properly escape special characters. Calling HttpUtility.JavaScriptStringEncode lets you do both:
alert(<%= HttpUtility.JavaScriptStringEncode("TEST", true) %>);
Note: If this JavaScript snippet appears inside an HTML attribute like onclick, you may need to change <%= to <%: so that the double quotes are also HTML encoded.
Why is it that I can use integers but not strings?
Because you need to put strings in quotes:
alert("<%: "TEST" %>");
The key here, as always, is to look at what the browser actually receives. With your original code, what the browser sees is:
alert(TEST);
...which is trying to use the variable TEST, not a literal string.
Now in the above, I've assumed the string won't have any " in it or other things that aren't valid within a JavaScript string literal. That's not usually a good assumption to make.
If you're using a recent version of .Net or using JSON.Net (see this question for details), you can output the string using a JSON serializer, which will ensure that anything within it that may be problematic is properly encoded/escaped. For instance, with JSON.Net, you might use:
// With JSON.Net
alert(<%: JsonConvert.ToString("TEST") %>);
// With a recent version of .Net
alert(<%: HttpUtility.JavaScriptStringEncode("TEST", true) %>);
The problem is in how this translates into JavaScript:
alert(<%: "TEST" %>);
becomes
alert(TEST);
This is a problem because it assumes there is a variable named TEST that you'd like to display the value of, but most likely, TEST is undefined. What you probably want to do is this:
alert('<%: "TEST" %>');
But since this is MVC 4, you can use the Json.Encode method to be a little cleaner, like this:
alert(<%: Json.Encode("TEST") %>);
Both of thse will translate to
alert('TEST');
This should display a message box with the string 'TEST'.
For some reason when I try writing to an HtmlDocument it strips some (not all) of the quotation marks of the string I am giving it.
Look here:
HtmlDocument htmlDoc = Webbrowser1.Document.OpenNew(true);
htmlDoc.Write("<HTML><BODY><DIV ID=\"TEST\"></DIV></BODY></HTML>");
string temp = htmlDoc.GetElementsByTagName("HTML")[0].InnerHtml;
The result of temp is this:
<HEAD></HEAD>
<BODY>
<DIV id=TEST></DIV></BODY>
It works exactly as it should except it is stripping the quotation marks. Does anyone have a solution on how to prevent or fix this?
There is no guarantees with innerHTML that it will return content identical to string you passed in. The innerHTML is constructed by browser using its HTML tree representation - so it will produce resulting string as it see fits.
So depending on your needs you can try to use some HTML parsing code that understands ID's without quotes around OR try to convince browser to use latest engine which more likely to produce innerHTML to you liking.
I.e. in your case it looks like at least IE9 renders your HTML as IE9:Quirks mode (that returns innerHTML in the shape your are not happy with), if you make valid HTML or force mode to IE9:Standard you'll get string with qoutes like
document.getElementsByTagName("html")[0].innerHTML
IE9:Standards - "<head></head><body><div id="TEST"></div></body>"
IE9:Quirks -
"<HEAD></HEAD>
<BODY>
<DIV id=TEST></DIV></BODY>"
You can try it yourself by creating sample HTML file and opening from disk. F12 to show dev tools and check out mode in the menu bar.
C# has a quirky feature though I'm not sure of it's name. Sorry i'm not sure of a vb equivalent.
Add an # at the beginning of a literal string to escape all characters.
htmlDoc.Write(#"<HTML><BODY><DIV ID="TEST"></DIV></BODY></HTML>");
Also, this isn't important but your html would not validate. All tags and attributes should be lower case. E.g.<HTML> should be <html>.
I have to deal with malformed Html and Html tags inside Html attributes:
<p class="<sometag attr="something"></sometag>">
Link
</p>
I tried using HtmlAgilityPack to parse out the content but when you load the above code into an HtmlDocument, the OuterHtml outputs:
<p class="<sometag attr=" something"="">">
Link
</p>
The p tag becomes malformed and the someothertag inside the href attribute of the a tag is not recognized as a node (although it's really text inside an attribute, I would like it to be recognized as a tag).
Is there something else I can use to help me parse bad Html like this?
it's not valid html, so i don't think you can rely on an html parser to parse it.
You may be asking a lot of a parser since this is probably a rare case. You may need to solve this on your own.
The major problem I see is that there are sets of double quotes within the attribute value. Is it guaranteed that the markup will always have a matching closing character for every opening? In other words, for every < will there be a > and for every opening " or ', a matching closing mark?
If that's the case, my suggestion would be taking the source for an HTML parser such as Html Agility Pack and adding some functionality to the attribute parsing. Use a stack; for every opening character, push it, then read until you find another opening or closing character. If it's opening, push it, if it's closing, pop it.
Alternately, you could add detection for the less-than and greater-than characters in the attribute value and not recognize the end of the attribute value until all the contained tags are closed.
One other possible solution is to modify the source markup before passing it to the parser and changing the illegal characters in the attribute values to escaped characters (ampersand-semicolon). Unfortunately, this would require doing some preliminary parsing on your part.