How to loop through ViewData with Javascript in ASPX View - javascript

I have populated ViewData item with an array of questions so that I can store the json data in local storage:
string[] jsonQuestions = new string[StudentExam.QuestionCount];
for (int i = 0; i < StudentExam.QuestionCount; i++)
{
jsonQuestions[i] = new JavaScriptSerializer().Serialize(StudentExam.QuestionsE[i]);
ViewData[i.ToString()] = jsonQuestions[i];
}
During testing I loaded the ViewData into the localstorage like this (hard coded) for the exact amount of questions:
localStorage.setItem("obj0", JSON.stringify(<%=ViewData["0"]%>));
localStorage.setItem("obj1", JSON.stringify(<%=ViewData["1"]%>));
localStorage.setItem("obj2", JSON.stringify(<%=ViewData["2"]%>));
localStorage.setItem("obj3", JSON.stringify(<%=ViewData["3"]%>));
//...etc.
In the view I am trying to now dynamically load the ViewData into the browser localstorage like this using javascript:
<script>
var mod = "<%=Html.Raw(Model.TotalNumberOfQuestionsForTest.ToString())%>";
for (var i = 0; i < mod; i++) {
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[i.toString()]%>));
};
</script>
Now this gave me an error that it cannot find i, since we "escaped" the client side code. So I changed it to :
for (var i = 0; i < mod; i++) {
var s = <%=ViewData[%>i.toString()<%]%>;
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
};
This is the part where I'm stuck at. I keep getting these errors on this line:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
Error 7 Invalid expression term ';'
and
Error 8 ; expected
and when I run the web app this is all I get on inspect element:
Compilation Error
Description: An error occurred during the compilation of a resource
required to service this request. Please review the following specific
error details and modify your source code appropriately.
Compiler Error Message: CS1525: Invalid expression term ')'
Source Error:
Line 278: localStorage.setItem( Line 279:
"obj" + i.toString(), Line 280:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>)); Line 281: Line 282:
};
Is there a way to escape the <%%> tags, into the javascript again for the javascript variable to use in the ViewData? Or another way to do this?
UPDATE:
I went on and played around with the code a bit more and this is the closest I have gotten to what I need to happen by doing it like this:
$(function () {
<% for (int i = 0; i < 1; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
<%}%>
});
So this does loop through my questions and put the value in where I needed, but the last issue I have is that now by having to put the javascript in quotations :
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
The last quotation mark is needed to close the string between the <%%> tags. but this quotation mark is giving me the error:
Invalid or unexpected token
as my javascript to store the localstorage looks like this now:
localStorage.setItem("obj1", JSON.stringify("my json query"))" //this quotation is the problem
Any assistance or help will be greatly appreciated.

I finally fix the problem. The issue with the quotation was that I was "stringifying" a string and the moment I removed the single quotation marks from the code:
$(function() {
<% for (int i = 0; i < Model.TotalNumberOfQuestionsForTest; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify("%>
<%=ViewData[i.ToString()]%>
<%="))"%>
<%}%>
The json object was successfully stored in the localstorage of the browser.

Related

Problems with IF condition

I'm trying to make a website that gathers information from APIs. The following code always evaluates to 'Beep Boop Beep! I can\t find the Wikipedia page with the API! :-( \n Anyways here is more info on...'! Anyone have any ideas why?
var geoNamesWiki = result.geoNamesWiki;
for (let j = 0; j < 30; j++) {
if (geoNamesWiki.geonames[j].feature == 'country' &&
(geoNamesWiki.geonames[j].countryCode == openCage.results[0].components["ISO_3166-1_alpha-2"] ||
geoNamesWiki.geonames[j].title.includes(openCage.results[0].components.country))) {
$('#summary').html(geoNamesWiki.geonames[j].summary);
$('#wikiLink').html(geoNamesWiki.geonames[j].wikipediaUrl).attr("href", "https://" + geoNamesWiki.geonames[j].wikipediaUrl);
} else {
$('#summary').html('Beep Boop Beep! I can\t find the wikipedia page with the API! :-( \n Anyways here is more info on' + openCage.results[0].components.country + ':');
$('#wikiLink').html('https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country)).attr("href", 'https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country));
}
}
Is suspect you have a string there at var geoNamesWiki = result.geoNamesWiki;
Try parsing it to a JSON object first var geoNamesWiki = JSON.parse( result.geoNamesWiki );
I found the answer thanks to #Bekim Bacaj! I was overwriting what I had already done, so just needed to add a break on the final line of the IF part.

Unable to parse valid json file

Logic
I've a JSON file as follows:
[
{
"title":"Article Title 1",
"url":"https://mywebsite.com/articles/article1.html",
"type":"codes"
},
{
"title":"Article Title 2",
"url":"https://mywebsite.com/articles/article2.html",
"type":"games"
},
{
"title":"Article Title 3",
"url":"https://mywebsite.com/articles/article3.html",
"type":"codes"
}
]
And I'm reading this file, then populating my html page for each item in the file (so there are 3 titles, means 3 containers on my page).
Problem
There was no error before, but now I get an error in console: *SyntaxError: JSON.parse: expected ',' or ']' after array element at line 12 column 2 of the JSON data*
BUT, it all works if there are only 2 articles! After adding the third dataset, there is error. The file format seems correct, there is "," at the right places, I converted it in different encodings but same error.
Code
Main Request:
I'm requesting JSON file on document load like this:
$(document).ready(function(){
var reqdata = new XMLHttpRequest();
reqdata.open('GET', "https://website.com/dat/data.json");
reqdata.onload = function() {
if (reqdata.status >= 200 && reqdata.status < 400) {
try{
var postData = JSON.parse(reqdata.responseText);
render_posts(postData); // this creates dynamic content in html
//console.log(postData);
} catch (err) {
alert(" JSON Parse Error :'( ")
}
} else { alert("JSON Requestion Server Error!") }
}; reqdata.onerror = function() { alert("JSON Request Connection Error!") };
reqdata.send();
});
Populating HTML:
This is called from the code above if JSON.parse is working. This part works fine, just for reference..
function render_posts(data) {
var htmldata = ""; var cardId = "";
for (var x = 0; x < data.length; x++) {
cardId = "card-type-" + data[x].type;
htmldata += "<div class='card' id='" + cardId + "' onclick='card_clicker(\"" + data[x].url + "\")'><div class='header'>" + data[x].title + "</div><div class='decor'></div></div>";
}
cardWrapper.insertAdjacentHTML('beforeend', htmldata);
}
Help: Any help is appreciated.. Can't figure out what's the real problem. The JSON file looks fine. I tried formatting it online, but same results. I'm quite new to AJAX. Tried other solutions on stackoverflow but still the same..
It's a small url decoding problem with JSON decode. Instead of adding the url like:
"url":"https://mywebsite.com/articles/article2.html"
It has to be given escape character backslash like this:
"url":"https:\/\/mywebsite.com\/articles\/article2.html"
And now everything is working fine!
Probably hard to notice extra characters somewhere
or
non-standard double quotes used
or
some other character that is not as you think it is (comma?)

Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue

Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: 񏳿က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!

Uncaught SyntaxError: Unexpected end of input line 1

Hi there I am trying to figure out what is going wrong. I am getting the error
Uncaught SyntaxError: Unexpected end of input in line 1
which is
var itemList = new Array();
A snippet of the code is included
var itemList = new Array();
$( document ).ready(function(){
var $newItem = $('#newItem');
var $itemList =$('#itemList');
var itemTouchStart;
var itemTouchEnd;
var itemTouchStartX;
var itemTouchEndX;
if( window.localStorage) //when application starts check if there is data
{
itemList = JSON.parse(window.localStorage.getItem('itemList'));
}
if(null !== itemList)
{
for (i=0;i<itemList.length; i++)
{
var itemNew = '<li data-key="'+ itemList[i].key +'"><span>'
+itemList[i].item +'</span></li>';
$itemList.append(itemNew);
}
}
else
{
itemList = new Array();
}
The line number of the error is wrong. The problem is at the end, you never close the function you're passing into ready or the call to it. Add }); at the end.
If that's missing only because you quoted a
...snippet of the beginning of the code...
...then the answer is that there's nothing wrong with line 1 that's apparent from your question. Weird errors like that can sometimes be down to invisible characters in the source, but I would expect to see an illegal character error rather than unexpected end of input. Unexpected end of input is pretty much what it says: You have a control structure of some kind open and haven't closed it when the parser reaches the end of the code text.
I find the Meteor JavaScript parser page is quite handy for diagnosing syntax errors.

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

Categories

Resources