Handle multiple requests with ICallbackEventHandler - asp.net

Is there any way to make multiple requests to the callback function in asp.net when using the ICallbackEventHandler? I need the results for each result, however, when I iterate through and call the function, I get the result only for the last call. Any way to make it return a result for each call?
This is what I am passing in via javascript:
function NoPostback() {
$(".spans").each(function(index, item) {
CallServer($(item).attr("myattr"));
});
}
In this, myattr is a custom attribute that holds a value (1..10). What I want returned is something like ('you said: ' + id) to be returned for each of the calls, so that I can go ahead and place them in the appropriate holders.
However, only one item is returned which is the final call made. For instance if there are 4 items, it returns only ('you said: 4').
Any idea on how to have all of them returned?
Thanks in advance.

Most Javascript AJAX frameworks either abort any subsequent requests if one is in progress, or they ignore previous requests and only handle the latest. The AJAX request itself will pass through the browser's XmlHttpRequest object, but the rest of the javascript code is running within the pages thread. Currently, there is no concurrent programming with javascript (however this is slated to change.)

Related

Chaining Handlers with MediatR

We are using MediatR to implement a "Pipeline" for our dotnet core WebAPI backend, trying to follow the CQRS principle.
I can't decide if I should try to implement a IPipelineBehavior chain, or if it is better to construct a new Request and call MediatR.Send from within my Handler method (for the request).
The scenario is essentially this:
User requests an action to be executed, i.e. Delete something
We have to check if that something is being used by someone else
We have to mark that something as deleted in the database
We have to actually delete the files from the file system.
Option 1 is what we have now: A DeleteRequest which is handled by one class, wherein the Handler checks if it is being used, marks it as deleted, and then sends a new TaskStartRequest with the parameters to Delete.
Option 2 is what I'm considering: A DeleteRequest which implements the marker interfaces IRequireCheck, IStartTask, with a pipeline which runs:
IPipelineBehavior<IRequireCheck> first to check if the something is being used,
IPipelineBehavior<DeleteRequest> to mark the something as deleted in database and
IPipelineBehavior<IStartTask> to start the Task.
I haven't fully figured out what Option 2 would look like, but this is the general idea.
I guess I'm mainly wondering if it is code smell to call MediatR.Send(TRequest2) within a Handler for a TRequest1.
If those are the options you're set on going with - I say Option 2. Sending requests from inside existing Mediatr handlers can be seen as a code smell. You're hiding side effects and breaking the Single Responsibility Principle. You're also coupling your requests together and you should try to avoid situations where you can't send one type of request before another.
However, I think there might be an alternative. If a delete request can't happen without the validation and marking beforehand you may be able to leverage a preprocessor (example here) for your TaskStartRequest. That way you can have a single request that does everything you need. This even mirrors your pipeline example by simply leveraging the existing Mediatr patterns.
Is there any need to break the tasks into multiple Handlers? Maybe I am missing the point in mediatr. Wouldn't this suffice?
public async Task<Result<IFailure,ISuccess>> Handle(DeleteRequest request)
{
var thing = await this.repo.GetById(request.Id);
if (thing.IsBeignUsed())
{
return Failure.BeignUsed();
}
var deleted = await this.repo.Delete(request.Id);
return deleted ? new Success(request.Id) : Failure.DbError();
}

http service not working for parallel requests

I am using an http service object to make servlet requests inside a method in flex. The method is being invoked simultaneously in parallel by two events. I could see that both requests have reached the servlet, but only one returns to the result event. Also this behaviours is not consistent . is it possible that parallel invocation of the httpservice result in loss of some requests? I am sure that both requests have reached the servlet and data is returned from it. Its just that the result event is not triggered in certain cases.
Thanks in advance.
Including code to describe the issue better.
Please find the method below. The below method "callServlet" is being invoked by two separate events
private var httpObj:HTTPService=new HTTPService();
private function callServlet(text:String):void{
Alert.show(text);
httpObj = new HTTPService();
httpObj.url=<servlet URL>;
httpObj.method="POST";
httpObj.resultFormat="xml";
httpObj.contentType="application/xml";
var requestString:String=text;
httpObj.request=requestString;
httpObj.addEventListener(ResultEvent.RESULT,onResultMethods);
httpObj.addEventListener(FaultEvent.FAULT,onFaultMethod);
httpObj.send();
}
Each time i call the method, i pass a different "text" variable. I can see that the alert displays the two different texts send to it. And as explained earlier, both requests does reach the servlet and a response is sent from servlet.
But the result event "onResultMethod" is invoked just once.It doesnt invoke the "faultonFaultMethod" either.
Yes, I have seen this problem before, if you are making multiple requests from flex, some of them will be lost, that was back in 3.0 times. Browsers has a way of stopping the number of http calls, they can allow maximum of 2 calls at a time(depends on the browser), may be chain your requests one after the other or use a singleton which manages your calls.
Thanks all for help. I think i ve got the issue though i cannot guarantee the answer to be right.
The above method is called twice by two events. The httpOject variable is a private var global to the method callServlet. The listeners created in this method are being removed in the result and fault handler methods(this is not shown in the code above).
So i believe when multiple events call the method simultaneously there is a chance that the global variable httpObj is modified by both the events and hence both events result in servlet call using the same httpservice object. When the first call returns to the resulthandler i am removing the listener for resulthandler due to which the second result does not reach the resulthandler method.
This is my assumption and as of now i dont have any better solution. Do let me know if anyone comes up with a better explanation.

custom validator against remote object

I have a need to validate a field against our database to verify unique-ness. The problem I seem to be having is that the validators doValidation() exits before we've heard back from database.
How can I have the validator wait to return its payload until after we've heard from the DB?
Or perhaps a better question might be (since I think the first question is impossible), how can I set this up differently, so that I don't need to wait, or so that the wait doesn't cause the validation to automaticallly return valid?
If you're using a remote object, you can specify the method call inside your remote declaration and assign a function to the result call. The result call only runs once the remote server returns something, so it won't be run before your validation.
Do your validation call in said result function call (which you will have to create) and you should be good. Your code should go something like this:
<s:RemoteObject id="employeeService"
destination="ColdFusion"
source="f4iaw100.remoteData.employeeData"
endpoint="http://adobetes.com/flex2gateway/"
result="employeeService_resultHandler(event)"/>
**<s:method name="dataCheckCall" result="dataCheckResult(event)"/>**
<s:RemoteObject />
And in your script:
function protected dataCheckResult(event:ResultEvent):void {
**doValidate();**
}
Edit: As soon as you call "dataCheckCall" the method will start running. If, for whatever reason, you want to call this WITHIN your validator, you can do so, and then dataCheckResult will run whenever it returns with it's payload (pretend doValidate is called elsewhere). I've left a message below as well.
You are trying to fit an asynchronous process (fetching data from a DB) into a synchronous process (checking all the validators in turn).
This won't work...
You'll need to either roll your own validator framework, or use a different method of determining the legality of your controls.
P.S. The MX validators are rubbish anyway!
What I've managed to do, seems to work, mostly. I don't like it, but it at least performs the validation against the remote source.
What I've done, then, is to use an 'keyUp' event handler to spin off the database lookup portion. In the meanwhile, I set up a string variable to act as some kind of a Flag, which'll be marked as 'processing'. When the response event fires, I'll examine its contents, and either clear the flag, or set it to some kind of other error.
Then, I have created a new 'EmptyStringValidator' will check the contents of this flag, and do its job accordingly.
Its indirect, but, so far, seems to work.

Loss of data in a JQuery call to a WebService

I've made a JQuery function that makes a call to a web service, the web service returns an int but somewhere between the web service returning its value and the JQuery picking it up the data is getting lost. below is my Jquery Function:
//Make a call to a web service to get the latest number of comments for this item
WebDesign.wfGetNumberOfCommentsForWebDesignItem(vintCurrentItemID,fGetNumberOfCommentsResult);
function fGetNumberOfCommentsResult(GetNumberOfCommentsResult){
//If the number of comments returned is not zero update the the number of comments
if (GetNumberOfCommentsResult != -1 && GetNumberOfCommentsResult != null)
{
vspanCommentsNumber.html(GetNumberOfCommentsResult);
}
else
{
vspanCommentsNumber.html("Unknown");
}
}
The variable GetNumberOfCommentsResult is null, not every time but I'd say about 10% of the time. I've recorded the data that the web service returns to the JavaScript and it's not null, it's valid data, so I'm at a loss as to how the JavaScript variable is set as null. Any ideas?
Can you confirm that you are running this in a callback, when the call to the webservice is guaranteed done, and not some timed method using setTimeout ? in the second case, a race condition could explain the variable results that you are getting.
Using FireBug (add-on for Firefox), on the Console tab you can see what data is being returned from the web service call, as well as what data is being passed.
First verify the data being moved back and forth. This is the easiest way to find a truly reproducible case.
Also, it would be helpful to see how you are calling the web service on the JavaScript side.
use fiddler or something similar to monitor http requests and actually grab the response when it is null, there has to be something different about it.

Synchronous calls using RemoteObject

Is there a way to make synchronous calls using RemoteObject in Flex?
All IO in Flex is asynchronous. The typical pattern to deal with this is to use an AsyncResponder. For instance:
var t:AsyncToken = remoteObject.methodCall();
t.addResponder(new AsyncResponder(resultEvent, faultEvent));
think twice when u want it to be synchronous.
Do u know what synchronous mean? it will FREEZE your application until it receive data. Unless u are pretty sure that your remote calling can receive return value immediately (super fast network connection).
if your function call depends on each other, i would suggest you implement a state machine. e.g.
after 1st async call, your state becomes STATE_1, and your next function call will check on this state variable, to decide next move (ignore the current call or carry on).
my 2 cents.
If you want synchronous behavior, just add a wait after you make the call.
EDIT: I've added code for the chaining behavior I was talking about. Just replace the result handler each subsequent time you call the remoteObject.
...
remoteObject.function1(...);
...
private var resultHandler1(event:ResultEvent):void
{
...
remoteObject.removeEventListener(resultHandler1);
remoteObject.addEventListener(ResultEvent.RESULT, resultHandler2);
remoteObject.function2(...);
}
private var resultHandler2(event:ResultEvent):void
{
...
}
I achieved the same in two ways: First, as said above the use of state machines. It may get tricky at times. Second, the use of command queues - I think this is the best way to do it... but the downside is that the UI may not be very reflective in this time.
you should perhaps try and make one request with with all the data u want to be recieved synchronous and then make the different classes that need data listen to the correct data for that class.
ex:
// request
remoteobject.GetData();
// on received request
private function receivedData(evt:ResultEvent):void
{
for each (var resultobject:ResultObjectVO in evt.result)
{
var eventModel:Object;
var event:DataEvents = new DataEvents(resultobject.ResultType);
event.data = eventModel;
eventdispatcher.dispatchEvent(event);
}
}
Something like this. Hopes this helps.
No, why would you wish to do that anyway.
Flex makes things asynchronous so that the user isn't forced to sit and wait while data is coming back.
It would be a very poor user expereince if each time an app requested data the user had to wait on it coming back before anything else could happen.
from comment
No you don't need synchronus behaivour. If you're making say 2 calls and call 2 comes in before call 1, but 2 relies on the data inside 1 then you're left with either don't fire off event 2 till 1 comes back (this will slow down your app - much like synchronus events) or implement a way to check that event 1 has come back in event 2's handler (there are many ways you could do this).
If you're firing off many events then why not have a wrapper class of some description that tracks your events and doesn't do anything on the responses until all events are back.
You can use the AsyncToken to keep track of individual requests, so if you are firing of loads at once then you can find out exaclty whats come back and whats not.
You all are somehow mistaken or not using flex from adobe, if you send 2 calls to the server, no matter if each has an individual resquestObject the second one will ONLY be returned after the first one finish, even if the second one takes 1 milisecond to process. Just try the fibonnaci 1/40 example.
Maybe if you call a synchronous XMLHttpRequest calling JavaScript on Flex, you can do this.

Resources