Where is defined which callback used for specific method in EClient - tws

I'm just starting to use the IB API in python. I'm able to retrieve all the desired results I want. However, one big problem arise to me. I don't fully understand how the linkage between the EClient class and a particular callback is made within the EWrapper class.
As of now I understand the workflow like this (high level):
An EClient instance makes a call to IB Gateway.
IB Gateway itself reach out to the IB Data centers to fetch data
Data comes back to IB Gateway
IB Gateway calls the callback, which is the interface
As far as I understand, IB Gateway triggers the correct Callback function. What I don't see from the documentation / source code is the connection between a EClient method and a the interface (callback) I override in my EWrapper class. When I trigger a specific method in step 1 above. How does IB Gateway know, which callback to run? Is this specified somewhere?

The callback functions which handle responses to each function called in EClient are hard-coded and detailed in the TWS API Reference Guide.
For instance, calling EClient.reqAccountUpdates causes responses to be returned in EWrapper::updateAccountValue and EWrapper::updatePortfolio, and you would need to override those functions in your own code.
TWS Python API Traders Academy Course
IBKR Recorded Webinars

Related

When to use RestRequest/RestResponse and when to use HttpResuest/HttpResponse?

When to use RestRequest/RestResponse and when to use HttpResuest/HttpResponse?
I am learning REST in Saleforce. I know there are methods like GET, POST, PUT, PATCH, DELETE.
But having confusion in these both and can I use Http request/Http Response instead of RestRequest/Restresponse ?
RestRequest/RestResponse are custom functions that allow you to listen for outside REST API requests from Apex code. You define a #RestResource annotated class and it functions much like the built in SF Rest API (although with the logic that you define). The different HTTP methods you mention are meant to respond (at a specific path) to different types of outside requests. A REST GET method should get a record. SF already has a REST API that follows these rules. They just enable you to write the logic to get the record (in this example) yourself, should you have some custom logic you wish to implement. Here is a link to the MDN docs that describe the different HTTP methods.
An HTTP request/response is when you wish to, from inside your APEX code, make a callout to some resource outside of SF.
In other words, think of RestRequest/RestResponse as a server method and HTTP as a client method.

Ninject: What is MvcModule: GlobalKernelRegistrationModule<OnePerRequestHttpModule>?

I'm seeing Ninject source code, I cannot understand the MvcModule (source code in github).
Why the OnePerRequestHttpModule stand as a generic template type? What does it mean for?
As you undoubtedly know, Ninject.Web.Common defines InRequestScope. This scope is for the activations that should live for the lifetime of a single http request. When an http request is finished, you might want to clear your activation cache for this request, but how do you know that the request has ended?
Well, the usual way of finding out is creating an Http Module and subscribing for the EndRequest event.
Suppose you've done that. Now you need to implement the event handler. In the event handler you want to clear your activation cache for this request, but how does the handler know where this activation cache is located? Ultimately this cache is part of ninject kernel, so if only you could get access to that.
But that's no problem, right? You are the implementer, so why don't you wire up your HttpModule during your kernel set-up?
Unfortunately there are quite a few problems with this approach. First, HttpModules have to be registered during the pre application startup up phase and there is no guarantee that your kernel will be created at that time. More importantly, what if you have multiple kernels? Does each of these going to create a new instance of HTTP Module? Better to avoid that.
So this is what ninject does.
The GlobalKernelRegistration class is almost static class that keeps per domain collection of kernels. It has one instance method - protected void MapKernels(Action<IKernel> action). This method executes and action on every kernel in the list. The kernel lists are kept per registration type, such as OnePerRequestHttpModule.
So what you (as a ninject author) do is derive OnePerRequestHttpModule from GlobalKernelRegistration and then in your implementation of EndRequest event handler you use this.MapKernels to execute your code to clean up the activation cache for the request.
GlobalKernelRegistrationModule class is a simple class that registers your generic type parameter (in your case OnePerRequestHttpModule) and the current kernel in the registry (GlobalKernelRegistration).
When you derive your MvcModule from GlobalKernelRegistrationModule<OnePerRequestHttpModule> this registration happens automatically when your MvcModule is loaded into the kernel.
You also need to make sure that OnePerRequestHttpModule is registered as an Http Module which is usually done in the bootstrap code inside NinjectWebCommon.cs or in NinjectHttpApplication (if the project is not using webapi).
It deactivates objects InRequestScope after the request ended.

How to guarantee that a particular delegate will handle a RestKit response

This question is about wrapping RestKit requests in custom objects, and whether or not I can guarantee that an object sending the RestKit request will also be used as a delegate when the response is returned.
I'm working with an abstruse REST API (Salesforce), and RestKit doesn't appear to handle some of Salesforce's peculiarities well -- for example, when you make a call to the Salesforce REST API, you might get back a partial dataset, and then be given a "nextRecordsUrl" that you must follow to get the next chunk. Others working with Salesforce and REST have run into the same issue (ref https://groups.google.com/forum/#!msg/restkit/HJNjB7I6WVM/8u5n7nHoJQUJ). I created a class to wrap the calls to Salesforce and automatically follow these links, and process the returned data sets correctly. The class instance registers itself as the delegate for the REST call.
The class I wrote works great on its own (when there's a single instance), but I'll be creating other classes and have several instances that will need to handle their data independently. I've read through the documentation and code (it's been a learning experience, I've only worked with ios for about a month now), but I can't see if it's guaranteed that a particular instance will respond as the delegate for its requests alone, or if it might accidentally pick up the responses for another instance.
For example, suppose I have instances A and B, both of which are making requests using RKObjectLoader, and which set themselves as delegates using loader.delegate = self;. Both are running simultaneously (asynchronous). Here's a potential flow I see:
A's RKObjectLoader makes call, registers self as delegate for response
RestKit framework sends request for A
B's RKObjectLoader makes call, registers self as delegate for response
RestKit framework sends request for B
... wait ...
RestKit framework gets response, and somehow determines that this response was from B's request, calling B as the delegate
B delegate methods get called
RestKit framework gets response, and somehow determines that this response was from A's request, calling A as the delegate
A delegate methods get called
I couldn't see how the RestKit framework would distinguish between responses from requests, and thereby ensure that the correct delegate instances get called. In other words, it appears to me that RestKit might get a response to a request, and then call any delegate it wants ... but that seems counterintuitive, and the framework author appears to be very sharp.
So, my questions:
If I have a class instance using RKObjectLoader and setting itself as the delegate, can I be guaranteed that it will be called when the response for that request comes in?
Can you point me to the actual implementation in the RestKit framework that handles this, so I can learn how it's done?
Thanks very much!
I haven't received an answer to this question, but in case somebody has the same question and comes across this, here's the answer: yes, RestKit does appear to match the correct delegate with the outgoing request.
I created a small class (with an (NSString*) identifier property that calls a service, and in the delegates I printed out the instance's identifier with the result. I confirmed that instance A's delegate method was handling instance A's call, and B's was handling B's, with several simultaneous calls.

Inject behavior into WCF After or During identification of WebGet Method to call

I am trying to solve a problem where i have a WCF system that i have built a custom Host, Factory host, instance providers and service behaviors to do authentication and dependency injection.
However I have come up with a problem at the authorisation level as I would like to do authorisation at the level of the method being called.
For example
[OperationContract]
[WebGet(UriTemplate = "/{ConstituentNumber}/")]
public Constituent GetConstituent(string ConstituentNumber)
{
Authorisation.Factory.Instance.IsAuthorised(MethodBase.GetCurrentMethod().Name, WebOperationContext.Current.IncomingRequest.Headers["Authorization"]);
return constituentSoapService.GetConstituentDetails(ConstituentNumber);
}
Basically I now have to copy the Call to IsAuthorised across every web method I have. This has two problems.
It is not very testable. I Have extracted the dependecies as best that I can. But this setup means that I have to mock out calls to the database and calls to the
WebOperationContext.
I Have to Copy that Method over and over again.
What I would like to know is, is there a spot in the WCF pipeline that enables me to know which method is about to be called. Execute the authorisation request. and then execute the method based on the true false value of the authorisation response.
Even better if i can build an attribute that will say how to evaluate the method.
One possible way to do what you want might be by intercepting requests with a custom IDispatchMessageInspector (or similar WCF extension point).
The trick there, however, is that all you get is the raw message, but not where it will be processed (i.e. the method name). With a bit of work, however, it should be possible to build a map of URIs/actions and the matching method names (this is how you'd do it for SOAP, though haven't tried it for WebGet/WebInvoke yet).

Serializing Delegates in WCF Using a Surrogate?

I have an idea, but I need help implementing it.
WCF does not support delegates in its contracts.
Instead it has a cumbersome callback contracts mechanism, and I'm looking for a way to overcome this limitation.
I thought about using a IDataContractSurrogate to replace each delegate in the contract with a token that will be serialized to the remote endpoint. There, the token will be deserialized into a generated delegate. This generated delegate will send a generic callback message which encapsulates all the arguments (that the delegate was invoked with).
The generic callback message will reach the first endpoint, and there the original delegate would be invoked with the arguments.
Here is the purposed (simplified) sequence:
A calls B-proxy.Foo(callback)
callback is serialized through a DelegateSurrogate.
The DelegateSurrogate stores the delegate in a dedicated delegate storage and replaces it with a token
The message arrives to B's endpoint
the token is deserialized through a DelegateSurrogate
The DelegateSurrogate constructs a generated delegate
B.Foo(generatedCallback) is invoked
Later, B is invoking generatedCallback(args)
generatedCallback(args) calls a dedicated generic contract on A's endpoint: CallbackContract-proxy.GenericCallback(args)
CallbackContract.GenericCallback(args) is invoked on A's endpoint
The original callback is retrieved from the storage and is invoked: callback(args)
I have already implemented this previously using service bus (NServiceBus), but I want to adapt the idea to WCF and I'm having hard time. I know how to implement steps 3,6,9 and 11. I don't know yet how to wire everything in WCF - especially the surrogate part.
That's it - I hope my question made sense, and that the collective wisdom here will be able to help me build this up.
Here's a sample usage for my desired solution:
// client side
remoteSvc.GetEmployeeById(17, emp =>
{
employees.Add(emp);
logger.log("Result received");
});
// server side
public void GetEmployeeById(int id, Action<Employee> callback)
{
var emp = getEmpFromDb(id);
callback(emp);
}
Actually, in this scenario I would look into the Expression API. Unlike a delegate, an Expression can be deconstructed at runtime. You can't serialize them by default, but a lot of work has been done in that space. It is also a bit like what a lot of LINQ providers do in the background, for example WCF Data Services.
Of course, another approach is simply to use a lambda expression as the hook for RPC, which is what I describe here. The code that implements this is freely available in the protobuf-net tree. You could customize this by using an attribute to associate your token with the method, and obtain the attribute from the MethodInfo.
IMO, the problem with delegates is that they are too tightly coupled to the implementation, so you can't have different implementations at each end (which is a common requirement).
Expressions have the advantage that lambdas still support intellisense etc, so you can do things like:
client.Invoke(svc => svc.Foo(123, "abc"));
and from that obtain Foo (the MethodInfo), 123 and "abc" separately, including captured variables, ref/out, etc. It all works.