I have a script that looks like this
Item i = db.Items.Find(Model.ItemID);
Component comp = db.Components.Find(Model.ComponentID);
<script type="text/javascript">
function clicked(e) {
var comp = #Html.Raw(JsonConvert.SerializeObject(comp.ComponentID)) || null;
var item = #Html.Raw(JsonConvert.SerializeObject(i.ItemID)) || null;
var compFSTK = #Html.Raw(JsonConvert.SerializeObject(comp.FSTK)) || null;
var itemFSTK = #Html.Raw(JsonConvert.SerializeObject(i.FSTK)) || null;
if (item == null) {
alert('item is null');
}
if (comp == null) {
alert('comp is null');
}
if(comp != null && item == null) {
var compQty = $('#compQTY').val();
var compDiff = #Model.comp_qty - compQty;
var compFuture = compFSTK - compDiff;
if (!confirm('Are you sure? Doing this will reduce component ' + comp.ComponentID + ' future stock to ' + compFuture))e.preventDefault();
}
else if(item!== null && comp == null ) {
var itemQty = $('#itemQTY').val();
var itemDiff = #Model.item_qty - itemQty;
var itemFuture = itemFSTK - itemDiff;
if (!confirm('Are you sure? Doing this will reduce item ' + item.ItemID + ' future stock to ' + itemFuture))e.preventDefault();
}
<script>
But whenever comp or i is null and is deserialized I receive the error of 'i/comp is null'
how can I make it so that it just sets the variable to null if it is null?
Related
As a part of a before upload control, I check if added files actually match the filetype that their extension describes.
I do a filecheck using a hidden element. and if it fails, it gets removed after formdata append.
I check the files at the backend too, but I also want to check via File Reader process. All functions like createItems or readItems and so on, are working in all other cases, meaning that they return output of either null, true or false. While I get output from image and video files, audio files not at all. It should work.
The question is: Does the file reader read audio files differently compared to video and image files?
The following is only a tiny block of the actual code.
Now the question is: Why it doesn't return output on audio files?.
quest0 & quest1 are UI elements. Which is the element that I pull the files from.
reader is "new FileReader".
what.filecount is added while page init as readonly property.
readItems gives output on all kind off files,
However the UI html doesn't get updated if it is the file type is audio/?
for (var oD = 0; oD < what.files.length; oD++)
{
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) { return; }
if (file_s.exec(file) && !what.multiple) { pL = true; }
else
{
if (what.files.length > what.filecount)
{
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null)
{ quest0.innerHTML = ('too many files added. only ' + what.filecount + ' are allowed.'); }
return;
}
pL = true;
if ( !lastform.includes(what.form.id) ) { pL = false; }
}
if (what.files && what.files[oD] && pL == true)
{
if (file_prev != null)
{
if (file_prev.getAttribute('data-src') == '')
{file_prev.setAttribute('data-src', file_prev.src); }
file_prev.src = file_backsrc;
}
reader.onload = function(e)
{
init();
if (typeof file_prev === 'undefined')
{
if (quest1 != null) { quest1.innerHTML = 'Error occoured'; }
return;
}
if (file_p == 'img' || file_p == 'video' || file_p == 'audio')
{ file_prev.src = e.target.result; }
if (file_p == 'canvas') { /*not yet*/ }
kill.classList.remove('invisible');
if (quest1 != null) { quest1.innerHTML = 'file done'; }
}
reader.onerror = function(e)
{
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
}
function waitfor(arr)
{
if (arr == null || arr.length == 0) { return; }
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null)
{ quest1.innerHTML = 'processing ' + file_p; }
}
if (what.multiple)
{
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++)
{
var oB = what.files[oD], oB0, oB1;
if (oB.type.includes('im')) { file_p = 'img'; }
if (oB.type.includes('au')) { file_p = 'audio'; }
if (oB.type.includes('vi')) { file_p = 'video'; }
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount)
{
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null)
{
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name))
{
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
}
}
}
}
if (stoargearr.length == what.files.length) { waitfor(stoargearr); }
else { reader.readAsDataURL(what.files[oD]); }
}
}
}
Does the "File reader API" react different on audio files as it does on video or image files?
Thanks for any help.
here it goes.
for (var oD = 0; oD < what.files.length; oD++) {
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) {
return;
};
if (file_s.exec(file) && !what.multiple) {
pL = true;
} else {
if (what.files.length > what.filecount) {
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null) {
quest0.innerHTML = 'too many files added. only ' + what.filecount + ' are allowed.';
};
return;
};
pL = true;
if (!lastform.includes(what.form.id)) {
pL = false;
};
};
if (what.files && what.files[oD] && pL == true) {
if (file_prev != null) {
if (file_prev.getAttribute('data-src') == '') {
file_prev.setAttribute('data-src', file_prev.src);
};
file_prev.src = file_backsrc;
};
reader.onload = function(e) {
init();
if (typeof file_prev === 'undefined') {
if (quest1 != null) {
quest1.innerHTML = 'Error occoured';
};
return;
};
if (file_p == 'img' || file_p == 'video' || file_p == 'audio') {
file_prev.src = e.target.result;
};
if (file_p == 'canvas') { /*not yet*/ };
kill.classList.remove('invisible');
if (quest1 != null) {
quest1.innerHTML = 'file done';
};
};
reader.onerror = function(e) {
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
};
function waitfor(arr) {
if (arr == null || arr.length == 0) {
return;
};
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
};
if (what.multiple) {
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++) {
var oB = what.files[oD],
oB0, oB1;
if (oB.type.includes('im')) {
file_p = 'img';
};
if (oB.type.includes('au')) {
file_p = 'audio';
};
if (oB.type.includes('vi')) {
file_p = 'video';
};
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount) {
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null) {
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name)) {
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
};
};
};
};
if (stoargearr.length == what.files.length) {
waitfor(stoargearr);
};
} else {
reader.readAsDataURL(what.files[oD]);
};
};
};```
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
This block gives no output on audio files.
UPDATED QUESTION
here is my code :
function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
$("#CXACNUM").val($("#CXACNUM").val("Data5"));
$("#CXACNAM").val($("#CXACNAM").val("Data4"));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
Data4 and Data5 is a field inside the database. these need to be display in the textbox. however as previous, it return output at the textbox as below :
Object Object
However when it display, it give me output :
[Object object]
This is because you are setting the returned value of val back to the same input, which is a jquery object
You need to simply do
$("#CXACNUM").val( JSON.stringify( Data5 ) );
Try using JSON.stringify as
$("#CXACNUM").val(JSON.sringify(Data5));
function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
var Data4Val=$(this).children("Data4").text();
var Data5Val=$(this).children("Data5").text();
$("#CXACNUM").val($("#CXACNUM").val(Data5Val));
$("#CXACNAM").val($("#CXACNAM").val(Data4Val));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
i have updated your code. hope this will work
If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false
So I have this JavaScript code that my friend gave me and I don't know what it does and he wants me to find out. So I was reading through it then I found this.
localStorage[_0xa5fd[8]] = JSON[_0xa5fd[14]](default_r_o)), !d[_0xa5fd[15]](localStorage[_0xa5fd[8]])) return;
r_o = JSON[_0xa5fd[11]](localStorage[_0xa5fd[8]]), jQuery[_0xa5fd[39]](r_o, function (_0xb434x1, _0xb434x2) {
void 0 == _0xb434x2 && _0xb434x1 == _0xa5fd[16] ? _0xb434x2 == _0xa5fd[12] : void 0 == _0xb434x2 && (_0xb434x2 = !1), typeof _0xb434x2 == _0xa5fd[17] ? (jQuery(_0xa5fd[5], jQuery(_0xa5fd[18] + _0xb434x1 + _0xa5fd[19])[_0xa5fd[6]]())[0][_0xa5fd[4]] = _0xb434x2, fnc = jQuery(_0xa5fd[5], jQuery(_0xa5fd[18] + _0xb434x1 + _0xa5fd[19])[_0xa5fd[6]]())[_0xa5fd[21]](_0xa5fd[20]), fnf = _0xb434x1 == _0xa5fd[22] || _0xb434x1 == _0xa5fd[23] ? _0xa5fd[24] : _0xa5fd[13], fnc = fnc[_0xa5fd[27]](0, fnc[_0xa5fd[26]](_0xa5fd[25])) + _0xa5fd[25] + fnf + _0xb434x2 + _0xa5fd[28], eval(_0xa5fd[29] + fnc)) : _0xb434x1 == _0xa5fd[30] ? jQuery(_0xa5fd[32])[_0xa5fd[31]](r_o[_0xa5fd[30]]) : _0xb434x1 == _0xa5fd[33] ? jQuery(_0xa5fd[34])[_0xa5fd[31]](r_o[_0xa5fd[33]]) : _0xb434x1 == _0xa5fd[16] && (r_o[_0xa5fd[16]] == _0xa5fd[35] ? (jQuery(_0xa5fd[37])[_0xa5fd[36]](_0xa5fd[4])
What I'm asking for is there a way to expand the arrays? Such as automaticly recoding the program with the arrays turned into the words?
Here is a js sample of such script:
<script>
var _0xa5fd = [ "failure", "onload", "responseXML", "responseText", "DOMParser", "text/xml", "parseFromString", "Microsoft.XMLDOM"];
/**
* #param {FileList} fileList
*/
function handleFiles(fileList)
{
var reader = new FileReader();
reader.onload = onReadFile;
reader.readAsText(fileList.item(0));
}
function onReadFile(event)
{
var fileContent = event.target.result;
var regex = /_0xa5fd\[(\d+)\]/ig;
var itemList;
var count = 0;
while ((itemList = regex.exec(fileContent)) != null)
{
var realValueKey = itemList[1];
var realValue = _0xa5fd[realValueKey];
if(realValue !== undefined)
{
var replaceRegex = new RegExp('_0xa5fd\\[' + realValueKey + '\\]', 'g');
fileContent = fileContent.replace(replaceRegex, "'" + realValue + "'");
}
count++;
}
console.log('finish: ' + count);
document.getElementById('scriptContent').innerText = fileContent;
}
</script>
and html code to select your obfuscated file:
<input type="file" id="input" onchange="handleFiles(this.files)">
<div id="scriptContent"></div>
Is there any angularjs or javascript function similiar to PHP str_pad_left ?
I could not get any result no input was written on screen.
Also i did not now if is it valid to pass the first parameter inside : {{}}.
I try use javascript str_pad function :
<script>
var num = str_pad({{ item.ID }}, 10,'','STR_PAD_LEFT')
document.write(num);
console.log('num '+num);
</script>
From this script :
function str_pad(input, pad_length, pad_string, pad_type) {
var half = '',
pad_to_go;
var str_pad_repeater = function(s, len) {
var collect = '',
i;
while (collect.length < len) {
collect += s;
}
collect = collect.substr(0, len);
return collect;
};
input += '';
pad_string = pad_string !== undefined ? pad_string : ' ';
if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
pad_type = 'STR_PAD_RIGHT';
}
if ((pad_to_go = pad_length - input.length) > 0) {
if (pad_type === 'STR_PAD_LEFT') {
input = str_pad_repeater(pad_string, pad_to_go) + input;
} else if (pad_type === 'STR_PAD_RIGHT') {
input = input + str_pad_repeater(pad_string, pad_to_go);
} else if (pad_type === 'STR_PAD_BOTH') {
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
input = half + input + half;
input = input.substr(0, pad_length);
}
}
return input;
}