EXTJS method errors out on string beginning with colon character - asp.net-mvc-3

I've inherited some EXTJS code on top of an ASP.NET MVC application and I'm trying to trace an error that occurs when a Ext.msg.prompt box has a string with a ":" character in front of it. Here's the method where the error seems to occur:
var casePrompt = function() {
Ext.Msg.prompt("Numb", "", function(btn, text) {
if (btn == "ok") {
numbID = text.trim().toUpperCase();
Ext.Ajax.request({
url: "/location/method/" + numbID,
method: "GET",
callback: function(options, success, response) {
var reply = Ext.decode(response.responseText);
if (success) {
listOpen(reply.Data);
} else {
errorMsg(reply, function(button, text) { numbID = ""; });
}
}
});
}
});
};
If a number goes into the box as expected, everything works fine. However, if someone enters that same number, or any valid number, with a ":" in front of it, the method errors out before it even returns to the controller. The error only says "Microsoft JScript compilation error: Syntax error" and highlights the following code in ext-all-debug.js:
doDecode = function(json){
return eval("(" + json + ;)');
}
Has anyone seen this before and know of a way to catch this error? I've tried to step through this in VS2010 without any luck yet.
Thank you!

I ended up just putting validation using regular expressions on the text string to catch anything that doesn't match a valid character. This took care of the colon and any other character, so mistaecko was right that it needed client side validation. This seems to have fixed the issue. Thank you for your comments!

Related

Outlook Add-in - AttachmentId is malformed

We've been having issues intermittently where we get an error when downloading email item content from EWS "AttachmentId is malformed". This is for ItemAttachment (Especially .eml files)
We could not figure why or how this is happening and noticed that the ones that were failing had + and / in the id's. Searching across the web landed me on this article. Although this article is from 2015, wondering if this is still happening.
This article blew my mind and made sense (kind of) and implementing the conversion of + -> _ and / -> - worked fine, for a while.
We are now receiving the same error 'AttachmentId is malformed' and again could not find why, I removed the custom sanitizer function that replaces these characters and it started working again.
I have no idea what and why is this happening and how to reliably get attachment content. Currently, I've moved the sanitizer into the catch handler, so if for some reason the AttachmentId fails, we'll retry it by sanitizing it. Will have to keep an eye on how many fail.
Any light on this issue will be really appreciated.
Update 1.0 - Sample Code
Front-end
//At this point we've got the email and got the files
//We call EWS only if file.type == Office.MailboxEnums.AttachmentType.Item
//For all other files we call REST endpoint ~ Office.context.mailbox.restUrl + '/v2.0/'......
//Sample code below if only for EWS call
let files = this.email.attachments || [];
files.map(file => {
this._getEmailContent(file)
.then(res => {
return res;
});
})
//Get content from EWS
_getEmailContent(file, _failed){
//attachmentId
//Most of the times this will be fine, but at times when Id has a `+` or `/` if fails, Was expecting the convertToEwsId to handle any sanitization required.
let attachmentId = Office.context.mailbox.convertToEwsId(file.id, Office.MailboxEnums.RestVersion.v2_0);
return this.getToken(EWS)
.then(token => {
return this.http.post(`${endpoint}/downloadAttachment`,{
token: token,
url: Office.context.mailbox.ewsUrl,
id: attachmentId
},{
responseType: 'arraybuffer',
}).then(res => res.data);
}).catch(err => {
attachmentId = attachmentId.replace(/\+/g, "_");
this._getEmailContent(attachmentId, true);
})
}
Back-end
[HttpPost]
public DownloadAttachment(Request model){
var data = service.DownloadAttachment(model);
if(data == null)
{
return BadRequest("Error downloading content...");
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
return data;
}
}
//Inside service
public byte[] DownloadAttachment(Request request){
var ser = new ExchangeService
{
Credentials: request.token,
Url = request.url
}
//Here it fails intermittently, returning AttachmentId is malformed.
var attachment = ser.GetAttachments(new [] {request.attachmentId}, null, null).First();
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load();
return fileAttachment.Content;
}
}

not getting response from ajax call in codeigniter

I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}

jQuery Ajax - Cant parse json?

I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});

KnockoutJS with IE8, occasional problems with Stringify?

A number of our users are still on IE8. Some of them occasionally are reporting problems when trying to post data to our servers (via a big button labeled "SAVE").
There is a script error that IE8 shows, which is: Unexpected call to method or property access, always pointing to the same line in the KnockoutJS 2.2.0 (debug, for now) library, line 450, which is as follows:
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
The method in my code that is at the root of the stack trace where this happens is this:
self.saveSingle = function (onSuccess, onFailure) {
ko.utils.arrayForEach(self.days(), function (day) {
day.close();
});
var jsonData = ko.toJSON(self);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: applicationLocation + "/api/assignmentapi/save",
data: jsonData,
success: function (data) {
self.status(data.Status);
self._isDirty(false);
ko.utils.arrayForEach(self.days(), function (day) {
day.clean();
});
if (onSuccess)
onSuccess();
},
error: function (data) {
onFailure();
},
dataType: "json"
});
};
We do strip out a number of properties that are not necessary to our POST as we convert the object to JSON, using this approach: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html
OurType.prototype.toJSON = function () {
var copy = ko.toJS(this);
delete copy.someUnneededProperty1;
delete copy.someUnneededProperty2;
delete copy.someUnneededProperty3;
delete copy.someUnneededProperty4;
return copy;
}
When it fails, it fails consistently on the line
var jsonData = ko.toJSON(self);
Now here comes the real mess:
It's not consistently happening
It doesn't happen to all IE8 users
We can't consistently reproduce it
The structure of our model that we're serializing doesn't appear matter
The jscript.dll is the current version for IE8
I was also experiencing this issue. Digging deeper I found a few things:
It was only failing occasionally, I found this by running the code in the console
The code in the data-bind was trowing an exception except the message was being swallowed due to IE8 gobbling up the message when using a try {} finally {} block (without catch).
Removing the try finally revealed a cannot parse bindings message.
When I started to get close to figuring out the issue (digging deep into the knockout code) it seemed to disappear in front of my eyes. This is the section of code it was failing on, catching the exception at the end of the code:
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function(node) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
default: return false;
}
},
'getBindings': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext);
return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function(node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function(bindingsString, bindingContext, node) {
try {
var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
return bindingFunction(bindingContext, node);
} catch (ex) {
throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
}
}
});
But yea, it stopped becoming reproducible so I came up with a hack that I tested and works earlier, just retrying the data parsing. So this:
data-bind="value: ko.computed(function(){return ko.toJSON(appViewModel.model()[0])})"
Became this:
data-bind="value: ko.computed(function(){while (true) { try { var json = ko.toJSON(appViewModel.model()[0]); return json; }catch(e){}}})"
Yes, it's very yucky, but it seems to do the trick until our users no longer need IE8 or the Knockout issue is fixed.
I have no idea if this will fix it, but you can use the mapping plugin to go between JS and JSON:
var mapping = {
'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
var viewModel = ko.mapping.toJS(data, mapping);
Taken from my answer to this question
I'd give this a try and see if it helps, as there's nothing obviously wrong in your approach.
Are you sure it's IE8 users who are hitting the issue? IE7 does not support JSON.stringify. You'll need to include the json2.js library to support IE7 and lower.

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

Resources