KnockoutJS mapping.fromJSON struggling with backslashes (file path values) - asp.net-mvc

I am trying to pass an object structure to my html, to bind to an href. The problem becomes file path (path to an .exe) are not understood because of '\'.
example below:
var categories = ko.mapping.fromJSON('[{"Applications":[{"Documentation":null,"ApplicationId":2,"Name":"PSSE","Description":"Model software","LocalExePath":"aecies://runApp?C:\Program Files (x86)\MyApp\app.exe"}],"Name":"foobar"}]');
Sorry if i messed up some syntax, i was taking a much larger json object and compressing it for an example, may have missed a bracket somewhere. Anyway, what comes out in categories for the ExePath, in the above case, is a string with the '\'s removed. If I force it to be '\\' for every '\', it fails saying don't understand identifier P (clearly breaking at C:\Program).
Martin's answer seems to be what I want, but what i put in the question was what do I need for fromJSON. The problem is that isn't what my code actually looks like. That is what is spit out from #Html.Raw(). Below I have added my actual code. The problem is I can't just add another replace all \ with four \'s because it adds \ to every JSON title. (ends up looking like [{\\\\"Applications\\\\")
var categories = ko.mapping.fromJSON(
'#Html.Raw(JsonConvert.SerializeObject(Model.Categories,
Formatting.None,
new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml, ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
).Replace("\\u0022", "\\\"").Replace("\"", "\\\""))');
The two possible fixes I have used are string.replace in the controller to format the data there. Or to have two slashes for every one in my database record. After it goes through the serialize and the Html.Raw, it ends up with the correct 4 amount if it has 2 in the database. Is there a third option that would allow me to store the actual path string (no extra slashes, 'C:\HelloDir\') in the database, but add a line to my Razor code to replace the slashes I care about.
Edit: stackoverflow didn't like me doing double slashes, which is perfect because there is lies the majority of my problem with the mapping.
Edit2: There is more to the question

You'll actually need four backslashes because you're going through 2 layers of decoding:
JavaScript string literal (turns \\ to \)
JSON decoding (turns \\ to \)
So you'll want:
var categories = ko.mapping.fromJSON('[{"Applications": [{"Documentation":null,"ApplicationId":2,"Name":"PSSE","Description":"Model software","LocalExePath":"aecies://runApp?C:\\\\Program Files (x86)\\\\MyApp\\\\app.exe"}],"Name":"foobar"}]');
you can see some more examples at
http://jsfiddle.net/gjb4h0jy/2/

For anyone looking for the solution to the slash problem, I have figured out that clearly that EscapeHtml entry was blowing things up. If I remove that and then handle specific special characters that I want escaped with Replace statements, everything works perfectly.
var categories = ko.mapping.fromJSON(
'#Html.Raw(JsonConvert.SerializeObject(Model.Categories,
Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
).Replace(#"\r\n", "").Replace(#"'", #"\'").Replace(#"/", #"\/").Replace(#"\\", #"\\\\").Replace("\"", "\\\""))');

Related

Split between two characters

I have this url, Being passed into javascript. I have it like this at the moment
var Link = '<%= #car.link.split('&')[1]%>';
The link has Id=63546&hjk I'm wanting to have the numbers only passed into the ticket.
So that 63546 is left. How would i go about this? It HAS to be between these two. Exactly Id= and &
Thanks
Does this split needs to done in rails side or in javascript side,. On both the sides using regex the string can be splitted to get only the numbers
On ruby side
s ="Id=63546&hjk"
s[/\d+/].to_i
=> 63546
On Javascript side
var regex = /\d+/g;
var string = "Id=63546&hjk";
var matches = string.match(regex);
document.write(matches);
Rather than try and pull apart the uri with regular expressions I would use the functions the standard library and rails give you for manipulating these things:
Rack::Utils.parse_query(URI.parse(#car.link).query)['Id']
This parse the URI, extracts the query string, uses rack to turn it into a hash of key value pairs and then extracts the one named Id. It doesn't rely on Id being exactly a certain position in the Url or anything like that.

Problems getting data from XML using Nokogiri and Rails

I'm trying to get information from a XML file with Nokogiri. I can retrieve file using
f = File.open("/my/path/file.xml")
cac=Nokogiri::XML(f)
And what a get is a fancy noko:file. My row tags are defined like
<z:row ...info..../>
like
<Nokogiri::XML::Element:0x217e7b8 name="z:row" attributes=[#<Nokogiri::XML::Attr:0x217e754 name="ID_Poblacio" value="3">
and I cannot retrieve the rows using either:
s=cac.at_xpath("/*/z:row") or
s=cac.at_xpath("//z:row") or
s=cac.at_xpath("//row") or
s=cac.at_xpath("z:row")...
Probably I'm really fool but I cannot figure out which can be the issue.
Does anyone face this problem?
Thanks in advance.
P:S I tried to paste my cac file directly from bash but something wierd happens with format so I remove it from question. If anyone can explain how to do it I will appreciate it.
Your XML element name contains a colon, but it is not in a namespace (otherwise the prefix and uri would show up in the dump of the node). Using element names with colons without using namespaces is valid, but can cause problems (like this case) so generally should be avoided. Your best solution, if possible, would be to either rename the elements in your xml to avoid the : character, or to properly use namespaces in your documents.
If you can’t do that, then you’ll need to be able to select such element names using XPath. A colon in the element name part of an XPath node test is always taken to indicate a namespace. This means you can’t directly specify a name with a colon that isn’t in a namespace. A way around this is to select all nodes and use an XPath function in a predicate to refine the selection to only those nodes you’re after. You can use a colon in an argument to name() and it won’t be interpreted as a namespace separator:
s=cac.at_xpath("//*[name()='z:row']")

Grails: User inputs formatted string, but formatting not preserved

I am just starting a very basic program in Grails (never used it before, but it seems to be very useful).
What I have so far is:
in X.groovy,
a String named parameters, with constraint of maximum length 50000 and a couple other strings and dates, etc.
in XController.groovy,
static scaffold = X;
It displays the scaffold UI (very handy!), and I can add parameter strings and the other objects associated with it.
My problem is that the parameters string is a long string with formatting that is pasted in by the user. When it is displayed on the browser, however, it does not retain any carriage returns.
What is the best way to go about this? I'm a very beginner at Grails and still have lots and lots of learning to do on this account. Thanks.
The problem is that the string is being displayed using HTML which doesn't parse \n into a new line by default. You need to wrap the text in <pre> (see: http://www.w3schools.com/tags/tag_pre.asp) or replace the \n with <br/> tags to display it correctly to the user.

Clean up & style characters from text

I am getting text from a feed that has alot of characters like:
Insignia&#153; 2.0 Stereo Computer Speaker System (2-Piece) - Black
4th-Generation Apple® iPod® touch
Is there an easy way to get rid of these, or do I have to anticipate which characters I want to delete and use the delete method to remove them? Also, when I try to remove
&
with
str.delete("&")
It leaves behind "amp;" Is there a better way to delete this type of character? Do I need to re-encode the text?
String#delete is certainly not what you want, as it works on characters, not the string as a whole.
Try
str.gsub /&/, ""
You may also want to try replacing the & with a literal ampersand, such as:
str.gsub /&/, "&"
If this is closer to what you really want, you may get the best results unescaping the HTML string. If so try this:
CGI::unescapeHTML(str)
Details of the unescapeHTML method are here.
If you are getting data from a 'feed', aka RSS XML, then you should be using an XML parser like Nokogiri to process the XML. This will automatically unescape HTML entities and allow you to get the proper string representation directly.
For removing try to use gsub method, something like this:
text = "foo&bar"
text.gsub /\b&\b/, "" #=> foobar

Why is this query string invalid?

In my asp.net mvc page I create a link that renders as followed:
http://localhost:3035/Formula/OverView?colorId=349405&paintCode=744&name=BRILLANT%20SILVER&formulaId=570230
According to the W3C validator, this is not correct and it errors after the first ampersand. It complains about the & not being encoded and the entity &p not recognised etc.
AFAIK the & shouldn't be encoded because it is a separator for the key value pair.
For those who care: I send these pars as querystring and not as "/" seperated values because there is no decent way of passing on optional parameters that I know of.
To put all the bits together:
an anchor (<a>) tag's href attribute needs an encoded value
& encodes to &
to encode an '&' when it is part of your parameter's value, use %26
Wouldn't encoding the ampersand into & make it part of my parameter's value?
I need it to seperate the second variable from the first
Indeed, by encoding my href value, I do get rid of the errors. What I'm wondering now however is what to do if for example my colorId would be "123&456", where the ampersand is part of the value.
Since the separator has to be encoded, what to do with encoded ampersands. Do they need to be encoded twice so to speak?
So to get the url:
www.mySite.com/search?query=123&456&page=1
What should my href value be?
Also, I think I'm about the first person in the world to care about this.. go check the www and count the pages that get their query string validated in the W3C validator..
Entities which are part of the attributes should be encoded, generally. Thus you need & instead of just &
It works even if it doesn't validate because most browsers are very, very, very lenient in what to accept.
In addition, if you are outputting XHTML you have to encode every entity everywhere, not just inside the attributes.
All HTML attributes need to use character entities. You only don't need to change & into & within script blocks.
Whatever
Anywhere in an HTML document that you want an & to display directly next to something other than whitespace, you need to use the character entity &. If it is part of an attribute, the & will work as though it was an &. If the document is XHTML, you need to use character entities everywhere, even if you don't have something immediately next to the &. You can also use other character entities as part of attributes to treat them as though they were the actual characters.
If you want to use an ampersand as part of a URL in a way other than as a separator for parameters, you should use %26.
As an example...
Hello
Would send the user to http://localhost/Hello, with name=Bob and text=you & me "forever".
This is a slightly confusing concept to some people, I've found. When you put & in a HTML page, such as in <a href="abc?def=5&ghi=10">, the URL is actually abc?def=5&ghi=10. The HTML parser converts the entity to an ampersand.
Think of exactly the same as how you need to escape quotes in a string:
// though you define your string like this:
myString = "this is \"something\" you know?"
// the string is ACTUALLY: this is "something" you know?
// when you look at the HTML, you see:
<a href="foo?bar=1&baz=2">
// but the url is ACTUALLY: foo?bar=1&bar=2

Resources