Json.net escaping or removing a character on SerializeObject - json.net

I am using Mvc 4 with Json.Net. I have an error message property with the follong content on the server:
"'Instalation Name' should not be empty."
On the client I am doing something like this:
'#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.Converters.StringEnumConverter()))';
and the output is the following:
"ErrorMessage":"'Instalation Name' should not be empty."
which is throwing error:
Expected ';'
I need a way to escape or remove the ' character. How can I do this? One way is to do custom JsonConverter ... Any other suggestions? Thanks!

I guess your #Html.Raw() is placed within <script></script>. So I suggest you just remove the ' characters around your JSON, so it looks like this:
<script type="text/javascript">
var v = #Html.Raw(...);
</script>
So the the variable v will receive the deserialized data directly.

Related

Webforms postback with multiple arguments

I wish to call the __doPostBack(eventTarget, eventArgument) function. In the code file I would then read the arguments as usual like this: Dim param As String = Request("__EVENTARGUMENT"). However this doesn't work for multiple arguments.
Someone here suggested that you could use a json or csv-list. Usually I would just choose a delimiter that sepeates my arguments. However in my case now the argument may contain any character, so I can't just decide on any delimiter, so I figured I'd use a JSON.
I tried this.
Markup:
<button type="button" id="btn_postbackButton" onclick="__doPostBack('btn_postbackButton', {one: 'someText', two: 'moreText'});">TestButton</button>
Code-File
If (IsPostBack) Then
Dim tgt As Object = Request("__EVENTTARGET")
Dim param As Object = Request("__EVENTARGUMENT") ' what datatype to use?
' [...]
' how to get arguments from json?
End If
Now how do I get my arguments back in the code? What datatype do I use for the parameters? Calling param.ToString() only returns [object Object]
What's more, the arguments are generated in the code file in my actual application, and there may be different ones and some may be missing, using a simple array doesn't work for me as you can't determine after the fact which array position coresponds to which argument. And regardless it still gives me [object Object].
When your button is clicked, the page sends the following HTML form fields:
__EVENTTARGET: btn_postbackButton
__EVENTARGUMENT: [object Object]
To get your json on the server side as a string, use the following button markup:
<button type="button" id="btn_postbackButton" onclick="__doPostBack('btn_postbackButton', '{one: \'someText\', two: \'moreText\'}');">TestButton</button>

Why is TrimStart not recognised in VisualStudio for ASP.NET?

I whant to use TrimStart for my string value like this: How to remove all zeros from string's beginning?
But TrimStart syntax is not recognise in VisualStudio. How to corectly generate it?
my code:
string str = parameters.Internal;
string s = str;
string no_start_zeros = s.TrimStart('0');
At the top of your .CS file do you have: using system; the string.TrimStart(); method is found in the system namespace, which is contained inside mscorlib.dll - you can also try referencing mscorlib.dll directly.
TrimStart() function is used to Removes all leading occurrences of a set of characters specified in an array from the current String object.
when visual studio version you are using ? as far as I know trimStart() support in almost all version from 1.1 to 4.5
check out below snippet for more detail
string szInput = "000YTHLKJH";
string output = szInput.TrimStart('0');
//output will be : YTHLKJH
Hope it helps

Stop the user entering ' char

I have a search page where I would like to stop the user entering a ' into textboxes, or replace it with a suitable character. Can anyone help me achieve this in asp.net vb ?
For example if a user searches for O'Reilly the search crashes with error:
Line 1: Incorrect syntax near 'Reilly'. Unclosed quotation mark before the character string ' '.
Thanks!
Use parameterized statements properly, and this will be handled for you.
Uh-oh. Use parameterized queries.
Use javascript onKeyDown event for the textbox - if the typed char is an apostrophe, you can simply drop it, so that it is not entered.
On the server side, you should simply replace "'" with "", just to make sure.
Be aware, that this is a very unsecure and unstable solution.
You can escape ' character with two of them '', e.g.
sql += "Surname LIKE '%" & name.Replace("'", "''") & "%' AND "
and SQL will accept it then.
However, I would suggest using parameters.
To actually answer the question, you can put an OnKeyDown javascript event on your textbox, detect the key that was pressed, and potentially cancel the input:
<input class="mainSearchBox" type="text" id="searchTerm" onkeydown="DetectIllegalKeys();">
<script>
function DetectIllegalKeys() {
if (event.keyCode == 222) {
event.returnValue = false;
}
}
</script>
to instead change apostrophes to an alternate character:
<input class="mainSearchBox" type="text" id="searchTerm" onkeyup="ChangeSingleQuote();">
<script>
function ChangeSingleQuote() {
var searchTerm = document.getElementById('searchTerm');
searchTerm.value = searchTerm.value.replace(/'/g, "e");
}
I highly recommend that you not use this approach for this problem!
Far better to fix the application to allow searches for titles of any character string.
You need to understand why the error occurs and not just solve it symptomatically. Read through Microsoft's own document about SQL Injection to find out how to protect yourself from this class of security flaws.
http://msdn.microsoft.com/en-us/library/ms998271.aspx
(As several others pointed out, parameterized statements is the solution.)

List Keys in JScript object using VBScript (Classic ASP)

I am using the JSON2 script in an asp page to parse JSON post data.
After parsing the data, I have an object in VBScript that allows for notations such as:
jsonData.key
I wish to parse through all the keys, however, I have no knowledge of the key names.
How would I go about doing this?
Example JSON:
{ "dbtable":"TABLE1", "dbcommand": "INSERT", "dbfilter": "ID" }
Thanks
You need to enumerate the property names of the object however this is a very alien thing to do in VBScript. You will need to build some other Jscript functions to assist converting the object into something more easily consumed in VBScript.
If the data is really as simplistic as the example in the question then you could use this function:-
function toDictionary(o)
{
var result = Server.CreateObject("Scripting.Dictionary");
for (var key in o)
result.Add(key, o[key]);
return result;
}
Now in VBScript:-
Dim myData: Set myData = toDictionary(jsonData);
For Each Key In myData
'' // Each Key is a property for jsonData
Next

Allowing dangerous query strings

I need to be able to allow query strings that contain characters like '<' and '>'. However, putting something like id=mi<ke into the the URL will output an error page saying:
A potentially dangerous Request.QueryString value was detected from the client (id="mi<ke").
If I first url encode the url (to create id=mi%3Cke) I still get the same error. I can get around this by putting ValidateRequest="false" into the Page directive, but I'd prefer not to do that if at all possible.
So is there anyway to allow these characters in query strings and not turn off ValidateRequest?
EDIT: I want to allow users to be able to type the urls in by hand as well, so encoding them in some way might not work.
I ran into a problem similar to this. I chose to base64 encode the query string to work around it.
using
System.Text.ASCIIEncoding.ASCII.GetBytes
to get the string as bytes
and then
System.Convert.ToBase64String
to turn it into a "safe" string.
To get it back, use:
System.Convert.FromBase64String
and then:
System.Text.ASCIIEncoding.ASCII.GetString
to reverse the polarity of the flow.
A little googling and I don't think so.
The exception seems to happen before your code even runs so you can't trap the exception.
I like the encoding as base64 or something idea.
Instead of URL encode, you could encrypt your id value to get around the issue. You will probably then need to URL encode the encrypted string.
I think you have some options. You could do as you indicate and turn off ValidateRequest. You would then need to take care of any input sanitization on your own. Or you could allow only certain characters and either have the user use a meta language to input them, i.e., instead of '<' use '[' and replace '>' with ']' or re-encoding these before submission yourself to the meta language (or Base64). Doing the re-encoding yourself would require Javascript be available for queries that used forbidden characters. You may still need to do input sanitization.
Quick stab at a jquery implementation:
$(document).ready( function() {
$('form').bind('submit', function() {
$('form' > 'input[type=text]').each( function(i) {
if (this.value) {
this.value = encode(this.value);
}
});
});
});
function encode(value) {
return ...suitable encoding...
}
I was working with the same problem, however i stumbled upon this javascript encoding method:
<script type="text/javascript">
var unencodedText = "This is my text that contains whitespaces and characters like and Ø";
var encodedText = "";
var decodedText = "";
alert('unencodedText: ' + unencodedText);
//To encode whitespaces and the 'Ø' character - use encodeURI
encodedText = encodeURI(unencodedText);
//We see that whitespaces and 'Ø' are encoded, but the '' is still there:
alert('encodedText: ' + encodedText);
//If we decode it we should get our unencodedText back
decodedText = decodeURI(encodedText);
alert('decodedText: ' + decodedText);
//To also encode the '' we use the encodeURIComponent
encodedText = encodeURIComponent(unencodedText);
//Now all the characters have been encoded:
alert('encodedText: ' + encodedText);
//To get our unencodedText back we now need to use the decodeURIComponent
decodedText = decodeURIComponent(encodedText);
alert('decodedText: ' + decodedText);
</script>
If you're dealing with more complicated symbols then you might want to use the encodeURIComponent for the url.
And i steal this gem from this link.

Resources