WebForm_DoCallback definition - asp.net

Is there a simple explanation on MSDN of WebForm_DoCallback function?
All I can find is this article http://msdn.microsoft.com/en-us/magazine/cc163878.aspx
which does include implementation of WebForm_DoCallback but doesn't do a good job explaining parameters themselves.
function WebForm_DoCallback(eventTarget, eventArgument,
eventCallback, context, errorCallback)
Like what exactly does it expect as an 'eventTarget'?
What is 'context'?
Etc...

WebForm_DoCallback appears to be the client-side counterpart to GetCallbackEventReference. It's generated with the same arguments, which are as follows:
target: The name of a server Control that handles the client
callback. The control must implement
the ICallbackEventHandler interface
and provide a RaiseCallbackEvent
method.
argument: An argument passed from the client script to the server
RaiseCallbackEvent method.
clientCallback: The name of the client event handler that receives the
result of the successful server event.
context: Client script that is evaluated on the client prior to
initiating the callback. The result of
the script is passed back to the
client event handler.
clientErrorCallback: The name of the client event handler that receives
the result when an error occurs in the
server event handler.
useAsync: true to perform the callback asynchronously; false to
perform the callback synchronously.
clientCallback and clientErrorCallback are client-side (usually javascript) functions with arguments in the form:
function clientCallback(returnmessage, context) {}
Where returnmessage is the response from the server (or error) and context is the same as the context passed in previously.
References:
MSDN: ClientScriptManager.GetCallbackEventReference Method
MSDN Magazine: Implications of Script Callbacks in ASP.NET
ESRI Developer Network: Page Postbacks and Client Callbacks

we can see something like this--
WebForm_DoCallback('__Page',parameter,callBack,context,null,false);
in the page resource file.
it seems the 'parameter' is a value type(string), while the context is a ref type.
anyway the "context" is rarely used.
the "Parameter" could only be a string, so you may need combine several values into it, and then separate it on the server.
while the data is transmitted to the server end, the relative class(as a subclass of interface 'ICallbackEventHandler') instant will be created, and the handler method will be called:
public void RaiseCallbackEvent(string eventArgument)
{
//deal with the eventArgument( the "parameter")
}
after that another method goes on and return a string back in the response..
public string GetCallbackResult()
{
//return command;
}
finally the async process raises the callback function( "callBack" in this case),which should has 2 input params:
function callBack(returnedStuff, context) {......}
and that's how it works
however I don't know where the javascript function "WebForm_DoCallback" is defined, so it may not work on the non-windows computers.

To what context do you need to use this with? The string is generated by the following method call in ClientScriptManager: http://msdn.microsoft.com/en-us/library/ms153110%28v=VS.100%29.aspx
Using this is what you can use to produce the above statement, without having to know the details.
HTH.

Related

Blazor Web code after await doesn't execute until the second time

In Blazor Web, I have a method called from a button that does an HttpClient call to an API and then populates a field (Result) on the form. When I call it the first time, nothing happens. When I call it the second time, the field gets populated. Chrome confirms that the API call is made successfully both times. It looks like the code after the await doesn't execute until the 2nd call. What am I doing wrong?
private async void DoAPICall()
{
VerificationReturnType ReturnData = await Http.GetFromJsonAsync<VerificationReturnType>(APIMethod);
Result = String.Format("TrustedCookie: {0}\r\nVerificationCookie: {1}\r\nError: {2}\r\n", ReturnData.TrustedCookie, ReturnData.VerificatonCookie, ReturnData.Error);
}
Fixed by changing the return type of the DoAPICall from void to Task. Even though the DoAPICall is functionally the event handler for the web form button onclick event and async event handlers usually have to have the void return type, in this (Blazor Web) context, the method must have the Task return type.
Also, (which was my first solution), don't try to call the GetFromJsonAsync method synchronously by appending .Result, like you might when writing a backend C# application. It will compile OK but blow up running in the browser.
Really hope this helps someone else with beginner mistakes - Blazor Web has such potential!

Is there a way that we can emit error or success manually on Future dart?

Something like SettableFuture/ListenableFuture java where we can control what to emit to the listener.
What I want to have is :
For example, I have a socket connection active.
I send(request) a message through socket in some function
The request also has its response, but it comes through onData(d) callback some where else not in this request funtion
I store the future in a key-value array after send
After the response on onData(d) I will get the future from the array and make it emit success or error appropriately
Normally you can make an asynchronous function either return a value (success) or throw an exception (either by throwing from a async function or by manually returning a Future.error).
If you have some existing Future that you don't control, you can't force it to succeed or to fail. You instead could make callers wait on a Future that you do control, and you could make your Future depend on the external one.
Completer can simplify some of that for you.

How do I pass additional params to dispatch()?

An API I'm writing accepts two arguments via URL - e.g /api/targets/foo/bar
app = webapp2.WSGIApplication([
('/api/targets/(\w*?)/(\w*?)$', MainPage),
], debug=True)
This fires off a GET handler:
def get(self, url_1, url_2):
#do some stuff
The cool thing here is that I can reference url_1 (foo) and url_2 (bar) inside my GET handler and they're defined for me.
I have another page which accepts both GET and POST requests. About 90% of what happens is the same in either case, so I've opted to use def dispatch() instead of having two separate handlers.
The problem here is that (even though I still have the regex blocks enclosed in my webapp2.WSGIApplication initialisation) they are no longer passed to the request handler, so I have to define them like this:
url_1= self.request.url.split("/")[3]
url_2= self.request.url.split("/")[4]
Which makes me feel like a peon. If I tell dispatch() to expect those two params, they never arrive - what do I need to do to mimic the get behaviour in dispatch?
It would be shorter to use:
arg_one = self.request.route_args[0]
arg_two = self.request.route_args[1]
Take a look at the webapp2 docs for the Request object, specifically the route_args and route_kwargs towards the bottom of the Request section.
This is an interesting use case. If I were you, I would keep get() and post() separate. If get() and post() share code, then I would move that code to a method of the RequestHandler that can be called from both get() and post(), or move the shared code into another class (I find a lot of my RequestHandlers just call methods on my model classes).
If you still want one method to replace both get() and post(), then instead of using dispatch(), I recommend you set the handler_method for the Route (see here in the docs). I would advise against handling these requests entirely in the dispatch() method, as that is supposed to, at some point, call the "handler method", which defaults to GET/POST/etc. based on the HTTP method, but you can set your own handler method to handle GET and POST and whatever else.
If you set the handler_method, it would look like this:
# note that handler_method is the method name as a string
app = webapp2.WSGIApplication([
('/api/targets/(\w*?)/(\w*?)$', MainPage, handler_method='handle_request'),
], debug=True)
In your handler:
class MainPage(webapp2.RequestHandler):
# note that your method signature MUST have args for the route args,
# or else an exception will occur
def handle_request(self, arg_one, arg_two):
# your code here
if self.request.method == 'GET':
# do GET stuff
elif self.request.method == 'POST':
# do POST stuff
This is nice because it leaves dispatch() unchanged. I like to think of dispatch() as pre- and post-processing to occur before/after calling get()/post()/whatever handler method you specify.

Handle multiple requests with ICallbackEventHandler

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.)

Best way to implement 1:1 asynchronous callbacks/events in ActionScript 3 / Flex / AIR?

I've been utilizing the command pattern in my Flex projects, with asynchronous callback routes required between:
whoever instantiated a given command object and the command object,
the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.
Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.
Currently I have done this using callback function references with specific kinds of signatures, but I was wondering if someone knew of a better (or an alternative) way?
Here's an example to illustrate my current method:
I might have a view object that spawns a DeleteObjectCommand instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say "deleteObjectSuccessHandler()" and "deleteObjectFailureHandler()" in this example) as callback function references to the command class's constructor.
Then the command object would repeat this pattern with its connection to the "data access" object.
When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its deleteObjectSuccessHandler() or deleteObjectFailureHandler() called.
I'll try one more idea:
Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):
public function deleteThing( id : String ) : DeferredResponse {
var deferredResponse : DeferredResponse = new DeferredResponse();
var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);
var result : Function = function( o : Object ) : void {
deferredResponse.notifyResultListeners(o);
}
var fault : Function = function( o : Object ) : void {
deferredResponse.notifyFaultListeners(o);
}
asyncToken.addResponder(new ClosureResponder(result, fault));
return localAsyncToken;
}
The DeferredResponse and ClosureResponder classes don't exist, of course. Instead of inventing your own you could use AsyncToken instead of DeferredResponse, but the public version of AsyncToken doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. ClosureResponder is just an implementation of IResponder that can call a function on success or failure.
Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures result or fault gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.
In the command it would look something like this:
public function execute( ) : void {
var deferredResponse : DeferredResponse = dao.deleteThing("3");
deferredResponse.addEventListener(ResultEvent.RESULT, onResult);
deferredResponse.addEventListener(FaultEvent.FAULT, onFault);
}
or, you could repeat the pattern, having the execute method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.
But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be Mate.
Many of the Flex RPC classes, like RemoteObject, HTTPService, etc. return AsyncTokens when you call them. It sounds like this is what you're after. Basically the AsyncToken encapsulates the pending call, making it possible to register callbacks (in the form of IResponder instances) to a specific call.
In the case of HTTPService, when you call send() an AsyncToken is returned, and you can use this object to track the specific call, unlike the ResultEvent.RESULT, which gets triggered regardless of which call it is (and calls can easily come in in a different order than they were sent).
The AbstractCollection is the best way to deal with Persistent Objects in Flex / AIR. The GenericDAO provides the answer.
DAO is the Object which manages to perform CRUD Operation and other Common
Operations to be done over a ValueObject ( known as Pojo in Java ).
GenericDAO is a reusable DAO class which can be used generically.
Goal:
In JAVA IBM GenericDAO, to add a new DAO, the steps to be done is simply,
Add a valueobject (pojo).
Add a hbm.xml mapping file for the valueobject.
Add the 10-line Spring configuration file for the DAO.
Similarly, in AS3 Project Swiz DAO. We want to attain a similar feet of achievement.
Client Side GenericDAO model:
As we were working on a Client Side language, also we should be managing a persistent object Collection (for every valueObject) .
Usage:
Source:
http://github.com/nsdevaraj/SwizDAO

Resources