AJAX call not hitting breakpoints in Async handler - ajax

I wrote a quick AJAX script to be called on a button press event which in turn invokes an asysnc handler to pull data from remote APIs. I modified that same script to invoke another handler that was not async and it works fine, I'm not sure why it's not hitting breakpoints in Visual Studio. Here's the AJAX script.
$("#RunNewShodanQuery").click(function (d) {
$.ajax(
{
type: "POST",
async: true,
url: "/Tools/Test?handler=UpdateResultsAsync",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
complete: function (res) {
console.log(res);
}
});
})
Here's the handler in question.
public async Task OnPostUpdateResultsAsync()
{
ModelState.Clear();
foreach (Entry e in _context.Entries)
{
// TBI
}
// Update Date of Last Scan so as not to make needless API calls spamming refreshes
DateOfLastScan = DateTime.Now;
// Dispose of the client once we're done
client.Dispose();
}
I've placed breakpoints in another test handler and modified the above AJAX with a URL to point to the new test handler and VS stops on breakpoints within that handler.
public void OnPostTestHandler()
{
int seven = 5;
}
I'm currently at a loss as to why Visual Studio isn't hitting breakpoints in the async handler. From the browser, I'm seeing entries return with status 200 and it appears that it is executing the handler code just not stopping in it. Any suggestions would be very welcome.

By convention, the name of the handler method is selected based the value of the handler parameter according to the scheme OnPost[handler]Async.
Which means that, for OnPostUpdateResultsAsync, the handler name is UpdateResults instead of UpdateResultsAsync.
For Razor page, PageActionInvoker will call DefaultPageHandlerMethodSelector.SelectHandlers to select the handler.
private List<HandlerMethodDescriptor> SelectHandlers(PageContext context)
{
var handlers = context.ActionDescriptor.HandlerMethods;
var candidates = new List<HandlerMethodDescriptor>();
// Name is optional, may not be provided.
var handlerName = GetHandlerName(context);
// The handler selection process considers handlers according to a few criteria. Handlers
// have a defined HTTP method that they handle, and also optionally a 'name'.
//
// We don't really have a scenario for handler methods without a verb (we don't provide a way
// to create one). If we see one, it will just never match.
//
// The verb must match (with some fuzzy matching) and the handler name must match if
// there is one.
//
// The process is like this:
//
// 1. Match the possible candidates on HTTP method
// 1a. **Added in 2.1** if no candidates matched in 1, then do *fuzzy matching*
// 2. Match the candidates from 1 or 1a on handler name.
// Step 1: match on HTTP method.
var httpMethod = context.HttpContext.Request.Method;
for (var i = 0; i < handlers.Count; i++)
{
var handler = handlers[i];
if (handler.HttpMethod != null &&
string.Equals(handler.HttpMethod, httpMethod, StringComparison.OrdinalIgnoreCase))
{
candidates.Add(handler);
}
}
// Step 1a: do fuzzy HTTP method matching if needed.
if (candidates.Count == 0 && AllowFuzzyHttpMethodMatching)
{
var fuzzyHttpMethod = GetFuzzyMatchHttpMethod(context);
if (fuzzyHttpMethod != null)
{
for (var i = 0; i < handlers.Count; i++)
{
var handler = handlers[i];
if (handler.HttpMethod != null &&
string.Equals(handler.HttpMethod, fuzzyHttpMethod, StringComparison.OrdinalIgnoreCase))
{
candidates.Add(handler);
}
}
}
}
// Step 2: remove candidates with non-matching handlers.
for (var i = candidates.Count - 1; i >= 0; i--)
{
var handler = candidates[i];
if (handler.Name != null &&
!handler.Name.Equals(handlerName, StringComparison.OrdinalIgnoreCase))
{
candidates.RemoveAt(i);
}
}
return candidates;
}

Related

How can I send a synchronous ajax request to my server in onunload function

I need to send a ajax request to my server before web page close, my send code is below.
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
When I call this function in a button onclick event, it works.
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
But when I call this function when the page is unloaded, it doesn't work.
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
When I debug the application, the JS execution stops after this line:
xmlHttpReg.send(null);
It didn’t go to the next line:
if(xmlHttpReg.readyState==4)
The “data” is also not sent to the server.
What is wrong with my program, can ajax be called in an onunload function? What should I do to make it work?

CRM - Internal Server Error: when working on multiple entities

So I have a custom action (an approval button) that can be triggered either when editing a single entity or for multiple entities when triggered from the entity list view.
The logic essentially removes one entity type and creates a different one with more fields and options available after approval.
The logic works just fine when it is triggered from the Form where there is just a single entity being edited.
However when the same logic is run from the list view and now I am iterating over multiple entities, there is in internal server error when I try to create the record for the new entity type (the one with more options). This makes no sense, I am calling out to a function which already works under a different scenario. And I am creating a new entity, not updating or deleting an existing one so there should be not locks or other concurrency issues.
The the error is gloriously uninformative and I can't see any logs anywhere that would help me debug this. Has anyone run into this before?
Edit
I have enabled CRM Trace Logging for errors (in the registry), however this does not help. This internal server 'Error' does not seem to be errory enough to show up in the logs.
Edit 2
Perhaps some code? The error happens on the SDK.REST.createRecord line, but only when it is run inside the loop of the click handler, when it is run from single entity form, it creates a record without issue.
PCL.EventParticipants = {
EventFormApproveParticipantClick: function (selectedItemIds, entityTypeName) {
debugger;
var anEventRequest,
requestId,
action,
event,
contact,
emailPref,
actualEmail;
console.log('Approval Clicked');
// Do this if we are working on a single event request
if (entityTypeName == null)
{
requestId = Xrm.Page.data.entity.getId();
action = Xrm.Page.data.entity.attributes.get("pcl_action").getValue();
var participant = PCL.EventParticipants.MakeParticipant(
Xrm.Page.data.entity.attributes.get("pcl_contact").getValue()[0].id,
Xrm.Page.data.entity.attributes.get("pcl_event").getValue()[0].id,
Xrm.Page.data.entity.attributes.get("pcl_name").getValue(),
Xrm.Page.data.entity.attributes.get("pcl_emailpreference").getValue(),
Xrm.Page.data.entity.attributes.get("pcl_selectedemail").getValue()
);
if (PCL.EventParticipants.Act(requestId, action, participant)) {
alert('Approval complete.');
}
return;
}
var opSuccess = true;
// When multiple requests are selected do...
for (var x = 0; x < selectedItemIds.length; x++) {
requestId = selectedItemIds[x];
SDK.REST.retrieveRecord(
requestId,
"pcl_eventrequest",
"pcl_eventrequestId,pcl_Action,pcl_Contact,pcl_Event,pcl_name,pcl_EmailPreference,pcl_SelectedEmail", null,
function (anEventRequest) {
requestId = anEventRequest.pcl_eventrequestId;
action = anEventRequest.pcl_Action.Value;
var participant = PCL.EventParticipants.MakeParticipant(
anEventRequest.pcl_Contact.Id,
anEventRequest.pcl_Event.Id,
anEventRequest.pcl_name,
anEventRequest.pcl_EmailPreference,
anEventRequest.pcl_SelectedEmail
);
if (!PCL.EventParticipants.Act(requestId, action, participant)) {
opSuccess = false;
}
},
function(error) {
alert('Could not retrieve selected event request: ' + requestId + ' Check that it has not been removed from the system. --> ' + error.message);
}, false
);
}
if (opSuccess) {
alert('Approvals completed.');
} else {
alert('One or more Approvals failed.');
}
},
Act: function (requestId, actionValue, participant) {
var opSuccess = false;
if (actionValue == '798330000') {
// Add action
opSuccess = PCL.EventParticipants.CreateEventParticipant(participant);
}
if (actionValue == '798330001') {
// Remove action
opSuccess = PCL.EventParticipants.RemoveEventParticipant(participant);
}
if (opSuccess == false) {
return opSuccess;
}
opSuccess = PCL.EventParticipants.RemoveParticipantRequest(requestId);
return opSuccess
},
CreateEventParticipant: function (eventParticipant) {
var existingParticipant = PCL.EventParticipants.RetrieveEventParticipantLike(eventParticipant.pcl_Event.Id, eventParticipant.pcl_Contact.Id);
if (existingParticipant != null) {
alert('Cannot approve this request. This contact is already participating in the selected event.');
return false;
}
var opSuccess = false;
SDK.REST.createRecord(
eventParticipant,
"pcl_eventparticipant",
function (result) {
opSuccess = true;
},
function(error) {
alert('Could not create event request with contactId: ' + eventParticipant.pcl_Contact.Id + ' and eventId: ' + eventParticipant.pcl_Event.Id + '. --> ' + error.message);
}, false
);
return opSuccess;
}, .....
}
Edit 3
I have modified the SDK.REST to have a 5th parameter which toggles whether or not the operation is synchronous or asynchronous. Passing false at the end of any operation makes the operation synchronous.

AngularJs 2 promises inside a watch the second one never works

I have 2 lists in my application and the user is supposed to drag and drop items from one list to another.
When the user drops an element from one of the lists to the other list a request has to be made to the server side code to update a field in the database (SelectedForDiscussion).
This is the code in my controller:
$scope.$watch("questionsDiscuss", function (value) {
var question = $.Enumerable.From($scope.questionsDiscuss).Where(function (item) { return !item.SelectedForDiscussion }).FirstOrDefault()
if (question != undefined) {
questionSelectionService.UpdateQuestionSelectionStatus(question.Id, true)
.then(function (output) {
var question = $.Enumerable.From($scope.questionsDiscuss)
.Where(function (item) { return item.Id == output.data.questionId })
.FirstOrDefault();
var index = $.Enumerable.From($scope.questionsDiscuss).IndexOf(question);
if (question != undefined)
if (output.data.result != "success") {
$scope.questionsDiscuss.splice(index, 1);
$scope.questionsReceived.splice(0, 0, question);
}
else {
question.SelectedForDiscussion = true;
$scope.questionsDiscuss[index] = question;
}
});
}
else {
var question = $.Enumerable.From($scope.questionsReceived).Where(function (item) { return item.SelectedForDiscussion }).FirstOrDefault();
if (question != undefined) {
questionSelectionService.UpdateQuestionSelectionStatus(question.Id, false)
.then(function (output) {
var question = $.Enumerable.From($scope.questionsReceived)
.Where(function (item) { return item.Id == output.data.questionId })
.FirstOrDefault();
var index = $.Enumerable.From($scope.questionsReceived).IndexOf(question);
if (question != undefined)
if (output.data.result != "success") {
$scope.questionsReceived.splice(index, 1);
$scope.questionsDiscuss.splice(0, 0, question);
}
else {
question.SelectedForDiscussion = false;
$scope.questionsReceived[index] = question;
}
});
}
}
}, true);
I have 4 javascript breakpoint placed at the following lines within Firebug:
2 of them at the following lines:
if (question != undefined) {
One at:
var question = $.Enumerable.From($scope.questionsDiscuss)
.Where(function (item) {
return item.Id == output.data.questionId
})
.FirstOrDefault();
And the other at:
var question = $.Enumerable.From($scope.questionsReceived)
.Where(function (item) {
return item.Id == output.data.questionId
})
.FirstOrDefault();
The following happens:
The breakpoints at:
if (question != undefined) {
are always reached.
The breakpoint at
var question = $.Enumerable.From($scope.questionsDiscuss)
.Where(function (item) {
return item.Id == output.data.questionId
})
.FirstOrDefault();
is also reached.
The other is never reached.
Both responses are OK(response code 200).
Everything should work perfectly but the then clause in the second promise is never reached.
Can anyone tell me what I am doing wrong?
The serverside appplication is an ASP.NET MVC application written in C#.
Edit 1:
I figured out why this was happening and I have a work around for it. I am stil interested in an actual solution.
The problem is angularjs throws an error then swallows it when calling $http for the second time. The error is:
digest alredy in progress
I think this is because in my directive I have this code:
dndfunc = function (scope, element, attrs) {
// contains the args for this component
var args = attrs.dndBetweenList.split(',');
// contains the args for the target
var targetArgs = $('#' + args[1]).attr('dnd-between-list').split(',');
// variables used for dnd
var toUpdate;
var target;
var startIndex = -1;
// watch the model, so we always know what element
// is at a specific position
scope.$watch(args[0], function (value) {
toUpdate = value;
}, true);
// also watch for changes in the target list
scope.$watch(targetArgs[0], function (value) {
target = value;
}, true);
// use jquery to make the element sortable (dnd). This is called
// when the element is rendered
$(element[0]).sortable({
items: 'div',
start: function (event, ui) {
// on start we define where the item is dragged from
startIndex = ($(ui.item).index());
},
stop: function (event, ui) {
var newParent = ui.item[0].parentNode.id;
// on stop we determine the new index of the
// item and store it there
var newIndex = ($(ui.item).index());
var toMove = toUpdate[startIndex];
// we need to remove him from the configured model
toUpdate.splice(startIndex, 1);
if (newParent == args[1]) {
// and add it to the linked list
target.splice(newIndex, 0, toMove);
} else {
toUpdate.splice(newIndex, 0, toMove);
}
// we move items in the array, if we want
// to trigger an update in angular use $apply()
// since we're outside angulars lifecycle
scope.$apply(targetArgs[0]);
scope.$apply(args[0]);
},
connectWith: '#' + args[1]
})
}
And there are 2 calls to apply at the end which trigger a new digest cycle I think.
Anyway I fixed it by adding this call before the calls to apply:
if (scope.updateLists != undefined)
scope.updateLists();
And moved all the code from the watch into the updateLists function.
Also because people have mentioned the service as having something to do with it I am pasting the relevant code within it:
GetQuestionsReceived: function (eid, criteria, page, rows) {
var promise = this.GetQuestionsReceivedInternal(eid,criteria, page, rows).then(function (response) {
// The return value gets picked up by the then in the controller.
return response;
});
// Return the promise to the controller
return promise;
},
GetQuestionsReceivedInternal: function (eid, criteria, page, rows) {
return $http({ method: 'GET',
url: '../QuestionManagement/GetQuestions?eventId='+eid+'&page=1&rows=5&'+serialize(criteria)
}).
success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
results = data;
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
if (window.console && console.log) {
console.log("Could not obtain questions received. Error:" + data + "Status:" + status + "Headers:" + headers + "Config:" + config);
}
});
},
GetQuestionsDiscuss: function (eid,criteria, page, rows) {
var promise = this.GetQuestionsDiscussInternal(eid,criteria, page, rows).then(function (response) {
// The return value gets picked up by the then in the controller.
return response;
});
// Return the promise to the controller
return promise;
},
GetQuestionsDiscussInternal: function (eid,criteria, page, rows) {
return $http({ method: 'GET',
url: '../QuestionManagement/GetQuestions?eventId=' + eid + '&page=1&rows=5&' + serialize(criteria)
}).
success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
response = data;
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
if (window.console && console.log) {
console.log("Could not obtain questions received. Error:" + data + "Status:" + status + "Headers:" + headers + "Config:" + config);
}
});
},
You have two very similar blocks of code, which could be generalized and placed in a function wrapper, leaving behind a very simple calling function.
If you can get everything into that form, then I think you will find it easier to debug.
Here is an attempt to do so :
function updateSelectionStatus(qA, qB, bool) {
var en = $.Enumerable.From(qA);
var question = en.Where(function (item) {
return bool ? !item.SelectedForDiscussion : item.SelectedForDiscussion;
}).FirstOrDefault();
if(question) {
questionSelectionService.UpdateQuestionSelectionStatus(question.Id, bool).then(function (output) {
if (output.data.result == "success") {
question.SelectedForDiscussion = bool;
}
else {
qA.splice(en.IndexOf(question), 1);
qB.unshift(question);
}
});
}
return question;
}
$scope.$watch("questionsDiscuss", function (value) {
if (!updateSelectionStatus($scope.questionsDiscuss, $scope.questionsReceived, true) {
updateSelectionStatus($scope.questionsReceived, $scope.questionsDiscuss, false);
}
}, true);
I may have made some false assumptions and simplified too much (eg. purging the inner $.Enumerable.From, which appears to reselect the same question as the outer), so you may well need to rework my code.
I'm advocating a principle here, rather than offering a solution.

AJAX XMLHttpRequest state undefined

In the following piece of JavaScript code, i'm executing GetData.php using AJAX. However, when i remove the comments to see the request object's state property, it turns up as undefined, although the PHP script is getting executed properly and my page is changing as i want it to. But i still need the state property. Any clue on what's going on here ?
function refreshPage()
{
var curr = document.getElementById('list').value;
var opts = document.getElementById('list').options;
for(var i=0;i<opts.length;i++)
document.getElementById('list').remove(opts[i]);
var request = new XMLHttpRequest();
request.onreadystatechange=
function()
{
if(request.readyState == 4)
{
//alert(request.state);
//if(request.state == 200)
{
fillOptions();
var exists = checkOption(curr);
var opts = document.getElementById('list').options;
if(exists == true)
{
for(var i=0;i<opts.length;i++)
if(curr == opts[i])
{
opts[i].selected = true;
break;
}
}
else
{
opts[0].selected = true;
}
refreshData();
}
/*else
{
alert(request.responseText);
//document.close();
}*/
}
}
request.open("GET","GetData.php?Address=" + address + "&Port=" + port,true);
request.send();
}
Do you mean request.status not request.state?
Try changing it to the .status and it should work just fine :)

AJAX - Return responseText

I've seen the myriad threads sprawled across the Internet about the following similar code in an AJAX request returning undefined:
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
I know that I'm supposed to "do something with" responseText like writing it to the HTML. The problem: I don't have that luxury. This bit of code is intended to be inside of a generic method for running fast AJAX requests that way all the code for making an AJAX request doesn't have to written out over and over again (~40×) with the chance of a minor problem here or there that breaks the application.
My method HAS to explicitly return responseText "or else." No writing to HTML. How would I do this? Also, I'd appreciate a lack of plugs for JQuery.
What I'm looking for:
function doAjax(param) {
// set up XmlHttpRequest
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
// send data
}
...
function doSpecificAjax() {
var param = array();
var result = doAjax(param);
// manipulate result
}
Doing a little research I came across this SOF post:
Ajax responseText comes back as undefined
Based on that post, it looks like you may want to implement your ajax method like this:
function doRequest(url, callback) {
var xmlhttp = ....; // create a new request here
xmlhttp.open("GET", url, true); // for async
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
Then, you can call that method like this...
doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function
if (err) {
return "";
} else {
return response;
}
});
This should return the responseText accurately. Let me know if this doesn't give you back the correct results.

Resources